根据类型组合列表中的元素并求和它们的值LINQ [英] Combine Elements in a List based on Type and Summate their Values, LINQ
本文介绍了根据类型组合列表中的元素并求和它们的值LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出此结构.
我基本上希望能够获取具有多种类型的项目的列表,并创建一个新列表来精简每个相似类型的值之和.但是,这些类型的名称是动态的(它们可以有或没有特定的顺序,并且没有有限的列表)
I basically want to be able to take a list of items with multiple types, and create a new list that condenses down the sum of the values of each like-type. However the names of the types are dynamic (they may or may not have a specific order, and there is no finite list of them)
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.
}
}
推荐答案
类似的东西应该可以工作.警告:我没有编译它.
Something like this should work. Warning: I didn't compile this.
items.GroupBy(i => i.Name)
.Select(g => new Item { Type= g.First().Name, Value = g.Sum(i => i.Value)})
.ToList()
这篇关于根据类型组合列表中的元素并求和它们的值LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文