Combine items in a list based on type and sum their values, LINQ

Given this structure.

Basically I want to be able to accept a list of items with multiple types and create a new list that compresses the sum of the values โ€‹โ€‹of each type. However, type names are dynamic (they may or may not have a specific order, and their final list is missing)

using System.Linq; using System.Collections.Generic; class Item { public ItemType Type; public int Value; public int Add(Item item) { return this.Value + item.Value; } } class ItemType { public string Name; } class Test { public static void Main() { List<ItemType> types = new List<ItemType>(); types.Add(new ItemType { Name = "Type1" }); types.Add(new ItemType { Name = "Type2" }); types.Add(new ItemType { Name = "Type3" }); List<Item> items = new List<Item>(); for (int i = 0; i < 10; i++) { items.Add(new Item { Type = types.Single(t => t.Name == "Type1"), Value = 1 }); } for (int i = 0; i < 10; i++) { items.Add(new Item { Type = types.Single(t => t.Name == "Type2"), Value = 1 }); } for (int i = 0; i < 10; i++) { items.Add(new Item { Type = types.Single(t => t.Name == "Type3"), Value = 1 }); } List<Item> combined = new List<Item>(); // create a list with 3 items, one of each 'type', with the sum of the total values of that type. // types included are not always known at runtime. } } 
+4
source share
4 answers

Something like this should work. Warning: I did not compile this.

 items.GroupBy(i => i.Name) .Select(g => new Item { Type= g.First().Name, Value = g.Sum(i => i.Value)}) .ToList() 
+7
source

It seems to me that you are trying to get a list of types along with their calculation (since the cost will always be 1 in your example). Below is the code that should do this:

 from i in items group i by i.Type into t select new { t.Key, TypeCount = t.Count() } 

This will return 3 objects (displayed as a table below):

 Type TypeCount -------- --------- Type1 10 Type2 10 Type3 10 

If the value will always be the same, then I believe that it is just like receiving an invoice.

0
source
 List<Item> combined = items.GroupBy(i => i.Type).Select(g => new Item { Type = g.Key, Value = g.Sum(i => i.Value) }).ToList(); 
0
source
 var itemsByType = items.ToLookup(i => i.Type); var sums = from g in itemsByType select new Item { Type = g.Key, Value = g.Sum(i => i.Value) }; var sumList = sums.ToList(); 
0
source

All Articles