c# - 使用策略将 List<T> 转换为 Dictionary

标签 c# linq dictionary lambda

我有 List < DTO >,其中 DTO 类如下所示,

 private class DTO
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }

我创建对象并将其添加到列表。

var dto1 = new DTO { Name = "test", Count = 2 };
var dto2 = new DTO { Name = "test", Count = 3 };
var dtoCollection = new List<DTO> {dto1, dto2};

现在我的要求是我需要从 dtoCollection 创建一个字典,它的键是 Name 字段,值是 Count 字段的总和。

例如,如果将上面的dtoCollection转换为Dictionary,条目应该是这样的

Key = "test" , Value = "5"

其中Value是对Name字段相同的Count字段求和

最佳答案

我想这会满足您的需求:

dtoCollection.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.Sum(y => y.Count))

关于c# - 使用策略将 List<T> 转换为 Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13377885/

相关文章:

C# 报表编辑列值

c# - 使用 SQLite 比较不同表中的值

linq - Entity Framework 6 - 如果查询不包含任何行,则检索 null 而不是默认值

c# - Dictionary.FirstOrDefault() 如何确定是否找到结果

c - 仅映射文件 C 的第一个字母

ios - 通过遍历字典显示随机问题

JavaScript 数据结构捕获一对值作为键及其值

c# - 仅绑定(bind)日期和时间

c# - ConvertTimeToUtc 总是关闭一小时

c# - 合并键匹配的键值对列表