开发者

Groupby list within the list using LINQ

开发者 https://www.devze.com 2023-02-23 12:26 出处:网络
I have two classes: class Customer { public string Name { get; set; } public string ZipCode { get; set; }

I have two classes:

class Customer
{
    public string Name { get; set; }
    public string ZipCode { get; set; }
    public List<Order> OrderList { get; set; }
}

class Order
{
    public string OrderNumber { get; set; }
}

Using LINQ, i want to get list of Orders group开发者_StackOverflow by ZipCode. If Zipcode "12121" has 10 customers and each has 2 orders then it should return me only one Zipcode with the list of 20 orders.

I am trying to do it like this but not able to figure out whats wrong

var orders = br.CustOrderList
.Select(r => new
{
    r.ZipCode,
    r.Name,
    r.OrderList
})
.GroupBy(x => new { x.ZipCode, x.OrderList}); 

Any help please?


This should do what you want:

var orders = br.CustOrderList
    .GroupBy(x => x.ZipCode)
    .Select(g => new
    {
        ZipCode = g.Key,
        Orders = g.SelectMany(x => x.OrderList)
    });


var orders = br.CustOrderList
.Select(r => new
{
    r.ZipCode,
    r.Name,
    r.OrderList
})
.GroupBy(x => x.ZipCode); 

You just want to group by the ZipCode so just group by that

Ah yea just try

var order = br.CustOrderList
              .GroupBy(x = x.ZipCode);

No need to select new items out of the list

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号