Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<T> to Dictionary with strategy

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

like image 521
Rockstart Avatar asked Dec 12 '22 20:12

Rockstart


2 Answers

I guess this will do what you need:

dtoCollection.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.Sum(y => y.Count))
like image 184
asgerhallas Avatar answered Jan 03 '23 23:01

asgerhallas


Following is the linq query

var dict = dtoCollection.GroupBy(x=>x.Name).ToDictionary(x=>x.Key, x=>x.Select(y=>y.Count).Sum());
like image 39
Tilak Avatar answered Jan 03 '23 23:01

Tilak