Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groupby list within the list using LINQ

Tags:

c#

linq

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 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?

like image 850
Asdfg Avatar asked Feb 24 '23 13:02

Asdfg


2 Answers

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)
    });
like image 72
Thomas Levesque Avatar answered Mar 12 '23 06:03

Thomas Levesque


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

like image 30
msarchet Avatar answered Mar 12 '23 05:03

msarchet