【问题标题】:Creating a Key/Value List with more than one value per key创建每个键具有多个值的键/值列表
【发布时间】:2012-03-05 14:40:32
【问题描述】:

我需要一个键/值列表,每个键有多个值!

我尝试过的:

SortedList<string,List<int>> MyList = new SortedList<string,List<int>>();    

但问题是我不能动态地将值添加到 SortedList 中的列表中?

foreach(var item in MyData)  { MyList.Add(item.Key,item.Value ????); }

我该如何解决这个问题?是否已经有具有此功能的列表?

问候 魔方

【问题讨论】:

标签: c# .net linq collections


【解决方案1】:

查看Lookup(Of TKey, TElement)类,其中

表示一组键,每个键映射到一个或多个值。

【讨论】:

    【解决方案2】:

    补充 Kirill 关于使用 Lookup 的有效建议:

    var lookup = MyData.ToLookup(item => item.Key);
    

    然后

    foreach (var entry in lookup)
    {
      string key = entry.Key;
      IEnumerable<int> items = entry;
    
      foreach (int value in items)
      {
        ...
      }      
    }
    

    【讨论】:

    • 感谢您的回答!我想要一个字符串列表作为键和整数作为值。我不是很了解用法!如何创建和添加项目?
    【解决方案3】:

    除了 ILookup,您还可以使用 Dictionary&lt;string,List&lt;int&gt;&gt;。 添加/设置项目时,您应该检查是否有该键的列表:

    Dictionary<string,List<int>> MyList;
    void AddItem(string key, int value){
    List<int> values;
    if(!MyList.TryGet(key, values)){
    values= new List<int>();
    MyList.Add(key, values);
    }
    values.Add(value);
    }
    

    遍历项目是:

    foreach (var entry in MyList)
    {
    string key = entry.Key;
    List<int> values = entry.Value;
    }
    

    如果键的值应该是唯一的而不是列表,则可以使用HashSet

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 2018-10-25
      相关资源
      最近更新 更多