Elegant way to create a nested Dictionary in C#

前端 未结 8 1831
深忆病人
深忆病人 2021-01-31 04:57

I realized that I didn\'t give enough information for most people to read my mind and understand all my needs, so I changed this somewhat from the original.

8条回答
  •  天涯浪人
    2021-01-31 05:38

    Define your own custom generic NestedDictionary class

    public class NestedDictionary: 
         Dictionary> {}
    

    then in your code you write

    NestedDictionary dict = 
           new NestedDictionary ();
    

    if you use the int, int, string one a lot, define a custom class for that too..

       public class NestedIntStringDictionary: 
            NestedDictionary {}
    

    and then write:

      NestedIntStringDictionary dict = 
              new NestedIntStringDictionary();
    

    EDIT: To add capability to construct specific instance from provided List of items:

       public class NestedIntStringDictionary: 
            NestedDictionary 
       {
            public NestedIntStringDictionary(IEnumerable<> items)
            {
                foreach(Thing t in items)
                {
                    Dictionary innrDict = 
                           ContainsKey(t.Foo)? this[t.Foo]: 
                               new Dictionary (); 
                    if (innrDict.ContainsKey(t.Bar))
                       throw new ArgumentException(
                            string.Format(
                              "key value: {0} is already in dictionary", t.Bar));
                    else innrDict.Add(t.Bar, t.Baz);
                }
            }
       }
    

    and then write:

      NestedIntStringDictionary dict = 
           new NestedIntStringDictionary(GetThings());
    

提交回复
热议问题