【问题标题】:Collection Like Dictionary<K, V> That allows Value Change像 Dictionary<K, V> 这样的集合,允许值更改
【发布时间】:2012-10-31 15:51:36
【问题描述】:

我理解为什么没有内置方法来执行此操作,但是我想要一个集合对象,它允许在枚举期间可能更改值。

想象一下:

Dictionary<string, List<string>> test =  new Dictionary<string, List<string>> {{"key", null}};

假设我在一个实现 IEnumberable 的类中有 20 个这样的类

我想使用 lambda 或简单的 foreach 遍历类并找到与键匹配的对象,然后将我的 List&lt;T&gt; 与 Value 参数一起存储。

【问题讨论】:

  • 您是否尝试过使用 ConcurrentDictionary?
  • if(test.ContainsKey("key"))test["key"] = myList; 有什么问题?为什么要枚举呢?
  • 您的意思是 20 个类似字典的对象,还是 20 个 string/List&lt;string&gt; 对?如果是后者,为什么要遍历对而不是直接通过键访问所需的对?
  • 谢谢大家,蒂姆,我没想到你会这样写,我正在寻找某种描述的方法:)。是时候看看用 lambda 编写查找部分了!

标签: c# dictionary


【解决方案1】:

您可能正在寻找一个名为 multimap 的集合。请参阅here 了解我的实现。

【讨论】:

    【解决方案2】:

    正如您所发现的,您无法通过Value 属性更改DictionaryEntry - 您必须使用Key 访问Item 访问器。

    一种选择是将您的Where 结果转换为一个数组,然后循环以获取匹配的Keys:

    Dictionary<string, List<string>> test =  new Dictionary<string, List<string>>
                                                 {{"key", null}};
    test.Add("newKey",null);
    
    var matches = test.Where(di => di.Key == "key").ToArray();
    
    foreach(var di in matches) {
        test[di.Key] = new List<string> {"one","two"};
    

    【讨论】:

    • 但是为什么不直接做if (test.ContainsKey("key")) test["key"] = new List&lt;string&gt;{...}呢?
    • @Rawling 因为 OP 提到使用 Lambda 来查找匹配的键。如果它只是一个简单的字符串匹配,那么可以简化。
    • 嗯,很公平。这是一个非常令人困惑的问题。
    【解决方案3】:

    您可以使用它来修改字典中的值:

    public static void ChangeValue(string indexKey,List<string> newValue)
    {
         if (test.ContainsKey(indexKey))
             keysDictionary[indexKey] = newValue;
    }
    

    【讨论】:

      【解决方案4】:

      您可以完全避免使用枚举器,例如

      var data = myEnumerable.ToArray();
      for(var i = 0; i < data.Length; i++) {
          // here you can manipulate data[i] to your heart's content
      }
      

      【讨论】:

        猜你喜欢
        • 2010-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-19
        相关资源
        最近更新 更多