4

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

4

2 回答 2

12

我想这会做你需要的:

dtoCollection.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.Sum(y => y.Count))
于 2012-11-14T11:30:04.177 回答
1

以下是 linq 查询

var dict = dtoCollection.GroupBy(x=>x.Name).ToDictionary(x=>x.Key, x=>x.Select(y=>y.Count).Sum());
于 2012-11-14T11:31:37.010 回答