如果键存在,则添加字典,如果不存在则添加新元素



我有

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

what I want

country = US,UK

所有变量的不同类型有点令人困惑,这对您编写代码没有帮助。我假设你有一个Dictionary<string, List<string>>,其中的关键是一个"语言"。这个值是该语言的国家列表。在寻求帮助时,将问题简化为再现该问题的最小集是非常有用的。

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

    尝试将dictionary["somelanguage"]键转换为existingValue
  • 如果它不存在,添加它并存储在同一个变量中。
  • List<string>添加到" someellanguage "关键。

代码看起来像这样:

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

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

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

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

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

使用字典接口

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

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

最新更新