基于类型组合列表中的元素并将它们的值汇总,LINQ

Cie*_*iel 4 c# linq

鉴于这种结构..

我基本上希望能够获取具有多种类型的项目列表,并创建一个新的列表,该列表压缩每个类似类型的值的总和.但是类型的名称是动态的(它们可能有也可能没有特定的顺序,并且没有有限的列表)

 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*man 7

这样的事情应该有效.警告:我没有编译它.

items.GroupBy(i => i.Name)
   .Select(g => new Item { Type= g.First().Name, Value = g.Sum(i => i.Value)})
   .ToList()
Run Code Online (Sandbox Code Playgroud)