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
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()
);