Home > OS >  C# flatten a list of objects
C# flatten a list of objects

Time:07-21

Given the following objects:

public class Order
{
    public int OrderID { get; set; }
    public int TotalPrice { get; set; }
    public List<OrderItem> Items { get; set; }
}

public class OrderItem
{
    public string Name { get; set; }
    public int Price { get; set; }
    public string SKU { get; set; }
}

Right now I have this structure:

[
    {
        "order_id": 1,
        "total_price": 700,
        "items": [
            {
                "name": "cellphone",
                "price": 500,
                "sku": "1s4f"
            },
            {
                "product_name": "airphones",
                "product_price": 200,
                "sku": "1ar4"
            }
        ]
    },
    {
        "order_id": 2,
        "total_price": 5000,
        "products_info": [
            {
                "name": "car",
                "price": 2500,
                "sku": "8y5t"
            },
            {
                "name": "battery",
                "price": 1500,
                "sku": "5g3g"
            },
            {
                "name": "insurance",
                "price": 1000
                "sku": "5r8f"
            }
        ]
    }
]

I want to the first order to be splitted to 2 orders, each one contains one item, and the second order to be splitted to 3 orders, with the same logic. What's the best clean and readable way of doing that?

CodePudding user response:

Gven an IEnumerable<Order> you can use LINQ Select and SelectMany

var result = orders.SelectMany(o => o.Items.Select(i => new Order{
   OrderID = o.OrderID,
   TotalPrice = i.Price,
   Items = new List<OrderItem> {
        new() { Name = i.Name, Price = i.Price, SKU = i.SKU }
   }
});

This will flatten your items into 5 separate orders, each with a single item. I have assumed you wanted the order TotalPrice to match the price of the single item it now has underneath it.

CodePudding user response:

What you can do is changing OrderItem and put a foreign Key in it

    public class OrderItem
{
    public string Name { get; set; }
    public int Price { get; set; }
    public string SKU { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; }
}

and then query like this var Items=_context.OrderItem.Tolist();

  • Related