Elegant way to create a nested Dictionary in C#

前端 未结 8 1810
深忆病人
深忆病人 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<K1, K2, V>: 
         Dictionary<K1, Dictionary<K2, V>> {}
    

    then in your code you write

    NestedDictionary<int, int, string> dict = 
           new NestedDictionary<int, int, string> ();
    

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

       public class NestedIntStringDictionary: 
            NestedDictionary<int, int, string> {}
    

    and then write:

      NestedIntStringDictionary dict = 
              new NestedIntStringDictionary();
    

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

       public class NestedIntStringDictionary: 
            NestedDictionary<int, int, string> 
       {
            public NestedIntStringDictionary(IEnumerable<> items)
            {
                foreach(Thing t in items)
                {
                    Dictionary<int, string> innrDict = 
                           ContainsKey(t.Foo)? this[t.Foo]: 
                               new Dictionary<int, string> (); 
                    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());
    
    0 讨论(0)
  • 2021-01-31 05:39

    You may be able to use a KeyedCollection where you define:

    class ThingCollection
        : KeyedCollection<Dictionary<int,int>,Employee>
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题