[英]Adding List of class into Dictionary C#
我有班級清單
List<Example> exampleList
其中已經包含了所有數據。 我需要創建一個字典
Dictionary<string, List<Example>> exampleDictionary
鍵必須為Example.Name,值必須為Example
這是下面的代碼。 問題是Example.Name可以相同。 我需要按名稱分組。 我需要遍歷列表,如果Name不存在,則添加新的Key和Value,否則將Value添加到Key。 我知道我將設置錯誤,但似乎無法找出正確的方法。
foreach(var x in exampleList)
{
if(!exampleDictionary.ContainsKey(x.Name)
exampleDictionary.Add(x.Name, x)
else
exampleDictionary[x.Name] = x;
}
我知道這段代碼不會建立。 我不確定如何設置。
您可以使用LookUp()
擴展方法:
var lookup = exampleList.ToLookUp(e => e.Name);
此方法返回一個Lookup<string, Example>
,這是一對多的字典,該字典將鍵映射到值的集合。
但是您的代碼可以按Name
固定分組,並將每個組添加到exampleDictionary
:
foreach (var g in exampleList.GroupBy(e => e.Name))
exampleDictionary.Add(g.Key, g.ToList());
要么
var exampleDictionary = exampleList.GroupBy(e => e.Name).ToDictionary(g => g.Key, g => g.ToList());
這應該工作
Dictionary<string, List<Example>> exampleDictionary = new Dictionary<string, List<Example>>();
foreach(var x in exampleList)
{
if(!exampleDictionary.ContainsKey(x.Name)) {
exampleDictionary[x.Name] = new List<Example>();
}
exampleDictionary[x.Name].Add(x);
}
您還可以使用ToDictionary
擴展方法來實現ToDictionary
功能:
Dictionary<string, List<Example>> exampleDictionary=exampleList.GroupBy(e => e.Name)
.ToDictionary(g => g.Key,g.ToList());
基本上與user469104(+1)相同
List<Example> le = new List<Example>() { new Example("one"), new Example("one"), new Example("two") };
Dictionary<string, List<Example>> de = new Dictionary<string,List<Example>>();
foreach (Example e in le)
{
if (de.ContainsKey(e.Name))
de[e.Name].Add(e);
else
de.Add(e.Name, new List<Example>() { e });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.