【问题标题】:Dictionary if Key exist append if not add new element C#字典如果键存在则追加如果不添加新元素C#
【发布时间】:2015-12-03 02:18:16
【问题描述】:

我有

Dictionary<String, List<String>> filters = new Dictionary<String, List<String>>();

它的值类似于country = us。到目前为止,我可以在不重复键时添加它。现在,当重复键 country 时。它表明密钥已经存在。

我想要的是如何在同一个键中添加多个值。我做不到。请提出一些建议。

for (int i = 0; i < msgProperty.Value.Count; i++)
{
    FilterValue.Add(msgProperty.Value[i].filterValue.Value);
    filterColumn = msgProperty.Value[i].filterColumnName.Value;
    filters.Add(filterColumn, FilterValue);
}

我想要什么

国家 = 美国、英国

【问题讨论】:

  • 考虑使用Lookup 而不是Dictionary
  • @w.b with List> ?
  • Lookup&lt;string, string&gt;
  • 意图不明确,不推荐Lookup。您不能向对象添加额外的值(它是一次性创建、多次读取的对象)。

标签: c# asp.net-mvc dictionary keyvaluepair


【解决方案1】:

您只需要检查字典中是否存在该值,如下所示:

if (!filters.ContainsKey("country"))
      filters["country"] = new List<string>();

filters["country"].AddRange("your value");

【讨论】:

  • 它正在覆盖旧值
  • 在向“国家”键插入新值之前,您需要创建一个逗号分隔值
【解决方案2】:

所有变量的不同类型有点令人困惑,这对您编写代码没有帮助。我假设您有一个Dictionary&lt;string, List&lt;string&gt;&gt;,其中键是“语言”,值是该语言的国家/地区列表,或其他。在寻求帮助时,将问题减少到重现问题的最小集合非常有用。

无论如何假设以上,就这么简单:

  • 尝试将dictionary["somelanguage"] 密钥插入existingValue。
  • 如果不存在,添加它并将其存储在同一个变量中。
  • 将List&lt;string&gt; 添加到字典的“somelanguage”键下。

代码将如下所示:

private Dictionary<string, List<string>> dictionary;

void AddCountries(string languageKey, List<string> coutriesToAdd)
{
    List<string> existingValue = null;

    if (!dictionary.TryGetValue(languageKey, out existingValue))
    {
        // Create if not exists in dictionary
        existingValue = dictionary[languageKey] = new List<string>()
    }

    existingValue.AddRange(coutriesToAdd);
}

【讨论】:

    【解决方案3】:

    利用IDictionary接口。

    IDictionary dict = new Dictionary<String, List<String>>();
    
    
    if (!dict.ContainsKey("key"))
          dict["key"] = new List<string>();
    
    filters["key"].Add("value");
    

    【讨论】:

      【解决方案4】:

      假设您正在尝试为关键国家/地区增加价值

      List<string> existingValues;
      if (filters.TryGetValue(country, out existingValues))
          existingValues.Add(value);
      else
        filters.Add(country, new List<string> { value })
      

      如果你的值是List&lt;string&gt;

      List<string> existingValues;
      if (filters.TryGetValue(country, out existingValues))
          existingValues.AddRange(values);
      else
          filters.Add(country, new List<string> { values })
      

      【讨论】:

      • 这包含双重查找,最好使用TryGetValue。
      • 字典的Value-Type是List&lt;string&gt;。你的代码不起作用。
      • @AmeyDeshpande 是您的价值列表 吗?
      • @ArghyaC 是列表 就是问题
      猜你喜欢
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 2020-03-09
      • 2012-09-20
      • 2010-12-14
      • 2023-03-16
      相关资源
      最近更新 更多