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

Roc*_*art 4 c# linq lambda 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字段获得的

asg*_*las 12

我想这会做你需要的:

dtoCollection.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.Sum(y => y.Count))
Run Code Online (Sandbox Code Playgroud)

  • 我的想法完全正确 并且不要忘记包含`System.Linq`! (2认同)