添加到字典中的字典

本文关键字:字典 添加 | 更新日期: 2023-09-27 18:24:02

我还不是一个特别自信的程序员,但我正在实现这一目标。

我的问题是我有

    static Dictionary<string, Dictionary<string, List<string>>> testDictionary = ...

如果Dictionary不包含当前键(字符串),我可以很容易地添加键和另一个已经填充的字典,比如…

   testDictionary.Add(userAgentResult, allowDisallowDictionary);

这很好,当我试图添加内部字典时,如果userAgentResultKey已经存在,我的问题就会出现。

我本来希望这样做。。。

    testDictionary[userAgentResult].Add(allowDisallowDictionary);

但是.Add方法需要两个参数,即字符串键和列表值。所以我继续写这个代码。。。

    //this list as the dictionary requires a list
    List<string> testDictionaryList = new List<string>();
    //this method returns a string
    testDictionaryList.Add(regexForm(allowResult, url));
    //this will add the key and value to the inner dictionary, the value, and then     
    //add this value at the userAgentKey
    testDictionary[userAgentResult].Add(allowDisallowKey, testDictionaryList);

这也是有效的,我的问题是这个字典被添加了很多次,当内部字典已经包含了试图添加的键时,它显然会出错。因此,当

添加到字典中的字典

我可能会通过拥有一个字典并连接键来简化这一点,从而"模拟"分组。

 string key = userAgentResult + allowDisallowKey;
 static Dictionary<string, List<string> testDictionary = ...
 testDictionary[key] = list;

你只需要管理一本字典。

在这种情况下,您需要做的是不向内部字典添加条目。您需要将该值添加到外部字典的键值对中。只是这一次,值恰好是另一个字典:)

testDictionary[userAgentResult] = allowDisallowDictionary;

也许我不明白你的问题。首先要确保字典是这样存在的:

if (!testDictionary.ContainsKey(userAgentResult))
    testDictionary[userAgentResult] = new Dictionary<string, List<string>>();
if (!testDictionary[userAgentResult].ContainsKey(allowDisallowKey))
    testDictionary[userAgentResult][allowDisallowKey] = new List<string>();

然后你可以自由添加这样的项目:

testDictionary[userAgentResult][allowDisallowKey].Add("some value");
testDictionary[userAgentResult][allowDisallowKey].AddRange(someValueList);

当使用嵌套字典时,我通常使用这种方法:

private static Dictionary<string, Dictionary<string, List<string>>> _NestedDictionary = new Dictionary<string, Dictionary<string, List<string>>>();
private void DoSomething()
{
    var outerKey = "My outer key";
    var innerKey = "My inner key";
    Dictionary<string, List<string>> innerDictionary = null;
    List<string> listOfInnerDictionary = null;
    // Check if we already have a dictionary for this key.
    if (!_NestedDictionary.TryGetValue(outerKey, out innerDictionary))
    {
        // So we need to create one
        innerDictionary = new Dictionary<string, List<string>>();
        _NestedDictionary.Add(outerKey, innerDictionary);
    }
    // Check if the inner dict has the desired key
    if (!innerDictionary.TryGetValue(innerKey, out listOfInnerDictionary))
    {
        // So we need to create it
        listOfInnerDictionary = new List<string>();
        innerDictionary.Add(innerKey, listOfInnerDictionary);
    }
    // Do whatever you like to do with the list
    Console.WriteLine(innerKey + ":");
    foreach (var item in listOfInnerDictionary)
    {
        Console.WriteLine("   " + item);
    }
}

您需要对内部字典执行与外部字典相同的操作。首先检查此密钥的列表是否已存在。如果没有创建,请使用已存在或已创建的列表。