![](/img/trans.png)
[英]How to transform a Dictionary<object, string> to a Dictionary<object, List<string>> with LINQ
[英]How to get a Dictionary<string, List<Object> with LINQ?
我有一個看起來像這樣的對象:
class Model
{
public string Category {get;set;}
public string Description {get;set;}
}
當前,我使用Linq獲取這些對象的全部列表,然后手動設置字典,如下所示:
List<Model> models = //get list from repository and then with linq order them by category and description
Dictionary<string, List<Model>> dict= new Dictionary<string, List<Model>>();
foreach (var m in models) {
if (dict.ContainsKey(m.Category))
{
dict[m.Category].Add(m);
}
else
{
dict.Add(m.Category, new List<Model> { m });
}
}
這樣,我可以使用鍵來訪問特定類別的所有模型。
有沒有一種方法可以直接使用LINQ查詢生成詞典?
謝謝!
是的,有一種方法,但是要完成此操作,您需要先將它們分組(以避免重復的鍵):
var dict = (from model in models
group model by model.Category into g
select g).ToDictionary(x => x.Key, x => x.ToList());
(雖然您在使用它,但我想知道它和.ContainsKey()方法的性能如何)
您可以使用Aggregate()來隱藏foreach邏輯,但是正如我上次向其建議的OP所說,這是Linq服裝中的一個循環。
關於什么:
var myDictionary = (from m in models
group m by m.Category into theGroup
select new {Key = m.Category, Value = theGroup.ToList()))
.ToDictionary(x=>x.Key, x=>x.Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.