Convert List to Dictionary with strategy

2019-06-26 02:49发布

I have List < DTO > where DTO class looks like this,

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

I create objects and add it to List.

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

Now my requirement is I need to create an Dictionary from the dtoCollection whose Key is Name field and value is Sum of Count fields.

For example, if you convert the above dtoCollection to Dictionary, the entry should be like

Key = "test" , Value = "5"

Where Value is obtained from summing up the Count fields whose Name fields are same

2条回答
The star\"
2楼-- · 2019-06-26 03:02

I guess this will do what you need:

dtoCollection.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.Sum(y => y.Count))
查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-26 03:07

Following is the linq query

var dict = dtoCollection.GroupBy(x=>x.Name).ToDictionary(x=>x.Key, x=>x.Select(y=>y.Count).Sum());
查看更多
登录 后发表回答