我有 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/