Grouping Linq List

for reporting purposes, I want to split the list of purchase orders into several lists. One list for each purchase address. I know that you can group the list at the purchase address, but my question is how to split the list at this purchase address into several lists and use these several lists to create separate report files.

the code:

(from o in orders group o by new {field1, field2, field3, field4} into og orderby og.Key.field1 select new ViewClass { purchaseAddress = og.Key.field1, product = og.key.field2, count = og.count }).ToList() 

Q: How to split the above list into multiple lists for each PurchaseAddress?

+4
source share
3 answers

There is a built-in function that, I think, does what you want. If I assume that your code is assigned to a variable called query , you can write this:

 ILookup<string, ViewClass> queryLists = query.ToLookup(x => x.purchaseAddress); 

This essentially creates a list of lists that you refer to as a dictionary, except that each value is a list of zero or more values. Sort of:

 IEnumerable<ViewClass> someList = queryLists["Some Address"]; 
+10
source

Just flip each group into a list.

 select new ViewClass { purchaseAddress = og.Key.field1, product = og.key.field2, count = og.count, List = og.ToList() }).ToList(); 

Oh, your grouping is one way for entities and another way for pages ... just regroup.

 List<ViewClass> classes = ( from o in orders group o by new {field1, field2, field3, field4} into og orderby og.Key.field1 select new ViewClass { purchaseAddress = og.Key.field1, product = og.key.field2, count = og.count }).ToList(); List<List<ViewClass>> regrouped = ( from c in classes group c by c.purchaseAddress into g select g.ToList() ).ToList(); 
+2
source

Another simple built-in function that you can use is the GroupBy function. It does a similar job like ToLookup, but that means your new list is IQuerable, not a dictionary and some other things (see Article for a good breakdown)

 var newList = orders.GroupBy(x => x.field1); 

This will return a list of lists grouped by the fields you specify.

0
source

All Articles