在字典中分组<string, IList<string>>

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

我有一个项目列表“listItems”,就像这样

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

想要获取字典,

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

我试过了

listItems.ToDictionary(x => x.Code, x => x.Value),但是这个returns一个Dictionary<string, string>,我想要一个Dictionary<string, IList<string>>

你可以先分组

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

如果需要,您可以投影字典中的值:

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