如何为复杂词典增加价值?

Nan*_* HE 5 c# dictionary

据我所知,为字典添加值的方法如下.

    Dictionary<string, string> myDict = new Dictionary<string, string>();

    myDict.Add("a", "1");
Run Code Online (Sandbox Code Playgroud)

如果我将"myDictDict"声明为下面的样式.

IDictionary<string, Dictionary<string, string>> myDictDict = new Dictionary<string, Dictionary<string, string>>();

myDictDict .Add("hello", "tom","cat"); ?// How to add value here.
Run Code Online (Sandbox Code Playgroud)

谢谢.

jas*_*son 8

正确的方法是这样的:

// myDictDict is Dictionary<string, Dictionary<string, string>>
Dictionary<string, string> myDict;
string key = "hello";
if (!myDictDict.TryGetValue(key, out myDict)) {
    myDict = new Dictionary<string, string>();
    myDictDict.Add(key, myDict);
}
myDict.Add("tom", "cat");
Run Code Online (Sandbox Code Playgroud)

这将提取与键对应的字典(hello在您的示例中)或在必要时创建它,然后将键/值对添加到该字典.您甚至可以将其提取到扩展方法中.

static class Extensions {
    public static void AddToNestedDictionary<TKey, TNestedDictionary, TNestedKey, TNestedValue>(
        this IDictionary<TKey, TNestedDictionary> dictionary,
        TKey key,
        TNestedKey nestedKey,
        TNestedValue nestedValue
    ) where TNestedDictionary : IDictionary<TNestedKey, TNestedValue> {
        dictionary.AddToNestedDictionary(
            key,
            nestedKey,
            nestedValue,
            () => (TNestedDictionary)(IDictionary<TNestedKey, TNestedValue>)
                new Dictionary<TNestedKey, TNestedValue>());
    }

    public static void AddToNestedDictionary<TKey, TNestedDictionary, TNestedKey, TNestedValue>(
        this IDictionary<TKey, TNestedDictionary> dictionary,
        TKey key,
        TNestedKey nestedKey,
        TNestedValue nestedValue,
        Func<TNestedDictionary> provider
    ) where TNestedDictionary : IDictionary<TNestedKey, TNestedValue> {
        TNestedDictionary nested;
        if (!dictionary.TryGetValue(key, out nested)) {
            nested = provider();
            dictionary.Add(key, nested);
        }
        nested.Add(nestedKey, nestedValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

我省去了防止null输入以保持清晰的想法.用法:

myDictDict.AddToNestedDictionary(
    "hello",
    "tom",
    "cat",
    () => new Dictionary<string, string>()
);
Run Code Online (Sandbox Code Playgroud)

要么

myDictDict.AddToNesteDictionary("hello", "tom", "cat");
Run Code Online (Sandbox Code Playgroud)

  • 通过将外部字典更改为"IDictionary",将内部字典更改为"TInnerDictionary,其中TInnerDictionary:IDictionary <TNestedKey,TNestedValue>,new()",可以使函数更通用(双关语). (3认同)
  • Woooohoooo我个人会选择这个答案为接受. (2认同)

Gon*_*alo 5

IDictionary<string,Dictionary<string,string>> myDictDict = new Dictionary<string,Dictionary<string,string>>();
Dictionary<string,string> dict = new Dictionary<string, string>();
dict.Add ("tom", "cat");
myDictDict.Add ("hello", dict);
Run Code Online (Sandbox Code Playgroud)