Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by in a dictionary<string, IList<string>>

I have a list of items "listItems", like this

Id Code Value
1  'a'  '1'
2  'a'  '2'
3  'b'  'x'
4  'b'  'y'

and want to obtain a dictionary,

'a' => '1', '2'
'b' => 'x', 'y'

I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

listItems.ToDictionary(x => x.Code, x => x.Value), but this returns a Dictionary<string, string>, I would like to have a Dictionary<string, IList<string>>

>Solution :

you can group by first

// gives Dictionary<string,IEnumerable<YourObject>>
listItems.GroupBy(x => x.Code).ToDictionary(x => x.Key);

you could project the values in the dictionary if need be:

// gives Dictionary<string,List<string>>
listItems.GroupBy(x => x.Code)
         .ToDictionary(
             x => x.Key, 
             x => x.Select(y => y.Value).ToList()
         );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading