相关疑难解决方法(0)

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

我有List <DTO>,其中DTO类看起来像这样,

 private class DTO
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我创建对象并将其添加到List.

var dto1 = new DTO { Name = "test", Count = 2 };
var dto2 = new DTO { Name = "test", Count = 3 };
var dtoCollection = new List<DTO> {dto1, dto2};
Run Code Online (Sandbox Code Playgroud)

现在我的要求是我需要从dtoCollection创建一个Dictionary,其Key是Name字段,value是Count of Count字段.

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

Key ="test",Value ="5"

其中Value是通过汇总名称字段相同的Count字段获得的

c# linq lambda dictionary

4
推荐指数
1
解决办法
1191
查看次数

标签 统计

c# ×1

dictionary ×1

lambda ×1

linq ×1