我有一個專案串列“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),但這會回傳一個Dictionary<string, string>,我想要一個Dictionary<string, IList<string>>
uj5u.com熱心網友回復:
你可以先分組
// 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()
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/405922.html
標籤:
上一篇:Linq中嵌套類的通用層次過濾器
下一篇:計算日期范圍的確切周數
