【问题标题】:Adding List of class into Dictionary C#将类列表添加到字典 C#
【发布时间】:2016-04-08 16:11:28
【问题描述】:

我有一个班级列表

List<Example> exampleList

其中已经包含所有数据。我需要创建一个字典

Dictionary<string, List<Example>> exampleDictionary

Key需要是Example.Name,值需要Example

下面是我的代码。问题是 Example.Name 可以相同。我需要按名称分组。我需要遍历我的列表,如果名称不存在,则添加新的键和值,否则将值添加到键中。我知道我设置错了,但我似乎无法找出正确的方法。

foreach(var x in exampleList)
{
   if(!exampleDictionary.ContainsKey(x.Name)
      exampleDictionary.Add(x.Name, x)
   else
      exampleDictionary[x.Name] = x;       
}

我知道这段代码不会编译。我不确定如何设置。

【问题讨论】:

    标签: c# list dictionary


    【解决方案1】:

    你可以使用LookUp()扩展方法:

    var lookup = exampleList.ToLookUp(e => e.Name);
    

    此方法返回一个Lookup&lt;string, Example&gt;,这是一个将键映射到值集合的一对多字典。

    但您的代码可以通过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());
    

    【讨论】:

    • 感谢您的解释和不同的选择。这正是我需要做的。
    【解决方案2】:

    这应该可以工作

    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);       
    }
    

    【讨论】:

      【解决方案3】:

      你也可以使用ToDictionary扩展方法来实现你想要的:

      Dictionary<string, List<Example>> exampleDictionary=exampleList.GroupBy(e => e.Name)
                                                                     .ToDictionary(g => g.Key,g.ToList());
      

      【讨论】:

      • 但是e.Name不是Key,会抛出异常
      【解决方案4】:

      与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 });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多