[英]Adding List of class into Dictionary C#
I have a list of my class 我有班级清单
List<Example> exampleList
Which already has all the data inside of it. 其中已经包含了所有数据。 I need to create a dictionary
我需要创建一个字典
Dictionary<string, List<Example>> exampleDictionary
The Key needs to be Example.Name and the value needs to Example 键必须为Example.Name,值必须为Example
Here is my code below. 这是下面的代码。 The problem is Example.Name can be the same.
问题是Example.Name可以相同。 I need to group by Name.
我需要按名称分组。 I need to loop through my list and if the Name does not exist add new Key and Value otherwise add the Value to the Key.
我需要遍历列表,如果Name不存在,则添加新的Key和Value,否则将Value添加到Key。 I know I am setting this up wrong but I can't seem to figure out the correct way of doing this.
我知道我将设置错误,但似乎无法找出正确的方法。
foreach(var x in exampleList)
{
if(!exampleDictionary.ContainsKey(x.Name)
exampleDictionary.Add(x.Name, x)
else
exampleDictionary[x.Name] = x;
}
I know this code wouldn't build. 我知道这段代码不会建立。 I am not sure how to set this up.
我不确定如何设置。
You can use LookUp()
extension method: 您可以使用
LookUp()
扩展方法:
var lookup = exampleList.ToLookUp(e => e.Name);
This method returns a Lookup<string, Example>
, a one-to-many dictionary that maps keys to collections of values. 此方法返回一个
Lookup<string, Example>
,这是一对多的字典,该字典将键映射到值的集合。
But your code can be fixed grouping by Name
and adding each group to exampleDictionary
: 但是您的代码可以按
Name
固定分组,并将每个组添加到exampleDictionary
:
foreach (var g in exampleList.GroupBy(e => e.Name))
exampleDictionary.Add(g.Key, g.ToList());
Or 要么
var exampleDictionary = exampleList.GroupBy(e => e.Name).ToDictionary(g => g.Key, g => g.ToList());
This should work 这应该工作
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);
}
You can also use ToDictionary
extension method to achieve what you want: 您还可以使用
ToDictionary
扩展方法来实现ToDictionary
功能:
Dictionary<string, List<Example>> exampleDictionary=exampleList.GroupBy(e => e.Name)
.ToDictionary(g => g.Key,g.ToList());
Basically the same as user469104 (+1) 基本上与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.