How to group data from table with multiple columns

162 Views Asked by At

I'm trying to group my data by using multiple columns in that way :

var groupedCustomers = listToProcess.GroupBy(cn => cn.CUST_NAME).Select(g => g.ToList()).ToList();

Grouping like that, I'm satisfied of what I'm getting as I can loop through all my objects and getting all their properties. However, as I'm supposed to group my table data using two fields (cust_name and cust_address), here's what I'm trying to do :

var groupedCustomers = listToProcess.GroupBy(cn => cn.CUST_NAME, ca => ca.CUST_ADDRESS).Select(g => g.ToList()).ToList();

Processing like that is also working but for each object, I'm only getting the address property.

Is there any other method to do that?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use an anonymous type as composite key:

var groupedCustomers = listToProcess
       .GroupBy(cn => new { cn.CUST_NAME, cn.CUST_ADDRESS })
       .Select(g => g.ToList()).ToList();
0
On

try

   var groupedCustomers = listToProcess
           .GroupBy(cn => new {CUST_NAME = cn.CUST_NAME, CUST_ADDRESS  = cn.CUST_ADDRESS })
           .Select(g => g.ToList()).ToList();