c# - 根据类型组合列表中的元素并求和它们的值,LINQ

标签 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.
    }
}

最佳答案

像这样的东西应该可以工作。警告:我没有编译这个。

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

关于c# - 根据类型组合列表中的元素并求和它们的值,LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3711224/

相关文章:

c# - 如何将 DateTime 转换为具有本地化小数秒的字符串?

c# - 如何使用 LINQ 从 List<Price> 中获取最接近的数字?

.net - 查找键的索引?词典.NET

.net - 过滤 LoadWith 结果

c# - 在内存方面,将一个长的非动态字符串存储为单个字符串对象还是让程序从重复部分构建它更好?

c# - 授权属性不适用于角色

c# - HttpNotificationChannel Open() 抛出 InvalidOperationException ("Failed to open channel")

c# - Log4Net,如何将自定义字段添加到我的日志记录中

c# - 使用 Find() 还是 Single() 从数据库中选择项目更好?

c# - 使用 LINQ 如何按 "calculated field"进行分组