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

时间:2009-12-28 03:13:59

标签: c# dictionary

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

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

    myDict.Add("a", "1");

如果我将“myDictDict”声明为下面的样式。

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

myDictDict .Add("hello", "tom","cat"); ?// How to add value here.
谢谢。

6 个答案:

答案 0 :(得分: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");

这将提取与键(您的示例中为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);
    }
}

我没有注意防范null输入以保持清晰。 用法:

myDictDict.AddToNestedDictionary(
    "hello",
    "tom",
    "cat",
    () => new Dictionary<string, string>()
);

myDictDict.AddToNesteDictionary("hello", "tom", "cat");

答案 1 :(得分: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);

答案 2 :(得分:2)

您可以使用C#3的集合初始值设定项,如下所示:

IDictionary<string, Dictionary<string, string>> myDictDict = new Dictionary<string, Dictionary<string, string>> {
    { "hello", new Dictionary<string, string> { "Tom", "Cat" } }
};

如果词典已经存在,您可以写

dict.Add("hello", new Dictionary<string, string> { "Tom", "Cat" });

请注意,仅当hello不是外部字典中的现有密钥时,此方法才有效。如果可能的话,你应该使用杰森的答案。

答案 3 :(得分:2)

要处理这种“简单”的方式:这样的事情:

    myDictDict.Add("some string", new Dictionary<string, string>());

    myDictDict["some string"].Add("another", "string");

直接回应OP的测试用例:(注意下面添加的编辑反映了纠正SLaks答案语法的愿望:在VS 2010 Beta 2中针对Framework 3.5 Client Profile进行了测试和验证的代码)

    // a simple case of creating an instance of a dictionary
    // of type <string, string>
    // and using .NET 3.0's (FrameWork => 3.5) collection initializer syntax
    Dictionary<string, string> twoStringDict = new Dictionary<string, string>()
    {
      {"key one", "value one"},
      {"key two", "value two"}, // note : an "extra" comma does not cause an error here
    };

    // more complex case as in the question on StackOverFlow
    // where dictionary is type <string, Dictionary<string, string>>
    // and using .NET 3.0's (FrameWork => 3.5) collection initializer syntax
    Dictionary<string, Dictionary<string, string>> myDictDict = new Dictionary<string, Dictionary<string, string>>()
    {
      { "key one",
            new Dictionary<string, string>() { { "innerKeyOne", "innerValueOne" }}},
      { "key two",
            new Dictionary<string, string>() { { "innerKeyTwo", "innerValueTwo" }}}
    };

    // syntax for adding another key value pair to the complex case
    myDictDict.Add("key three", new Dictionary<string, string>() { { "innerKeyThree", "innerValueThree" }});

答案 4 :(得分:1)

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

var subDict = new Dictionary<string, string>();
myDictDict .Add("hello", subDict ); 
subDict.Add("tom", "cat");

答案 5 :(得分:1)

您可以像这样定义扩展方法:

static void Add(this IDictionary<string, Dictionary<string, string>> dict, string a, string b, string c){
    dict.Add(a, new Dictionary<string,string>(){{b,c}};
}

然后将其用作:

myDictDict.Add("hello", "tom","cat");