我有 List 其中 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 创建一个字典,其键是 名称 字段,值是 计数 字段的总和。例如,如果将上面的 dtoCollection 转换为 Dictionary,则条目应为 Key = "test" , Value = "5"其中 Value 是通过汇总 计数 字段,其 名称 字段相同 最佳答案 我想这会做你需要的: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/
10-12 22:16