如果没有添加新元素C#,如果Key存在,则为Dictionary

时间:2015-09-07 13:41:04

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

我有

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

我想要什么

  

country = US,UK

4 个答案:

答案 0 :(得分:10)

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

无论如何假设上述情况,就像这样简单:

  • 尝试将dictionary["somelanguage"]密钥设为existingKey
  • 如果它不存在,请添加它并将其存储在同一个变量中。
  • List<string>添加到“somelanguage”键下的字典中。

代码如下所示:

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

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

    existingKey.AddRange(coutriesToAdd);
}

答案 1 :(得分:2)

您只需要检查字典中是否存在天气值,或者您可以使用以下代码检查

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

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

答案 2 :(得分:1)

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

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

如果您的值为List<string>

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

答案 3 :(得分:1)

使用IDictionary界面。

IDictionary dict = new Dictionary<String, List<String>>();


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

filters["key"].Add("value");