Elegant way to create a nested Dictionary in C#

前端 未结 8 1815
深忆病人
深忆病人 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:36

    Use BeanMap's two key Map class. There is also a 3 key map, and it is quite extensible in case you need n keys.

    http://beanmap.codeplex.com/

    Your solution would then look like:

    class Thing
    {
      public int Foo { get; set; }
      public int Bar { get; set; }
      public string Baz { get; set; }
    }
    
    [TestMethod]
    public void ListToMapTest()
    {
      var things = new List
                 {
                     new Thing {Foo = 3, Bar = 3, Baz = "quick"},
                     new Thing {Foo = 3, Bar = 4, Baz = "brown"},
                     new Thing {Foo = 6, Bar = 3, Baz = "fox"},
                     new Thing {Foo = 6, Bar = 4, Baz = "jumps"}
                 };
    
      var thingMap = Map.From(things, t => t.Foo, t => t.Bar, t => t.Baz);
    
      Assert.IsTrue(thingMap.ContainsKey(3, 4));
      Assert.AreEqual("brown", thingMap[3, 4]);
    
      thingMap.DefaultValue = string.Empty;
      Assert.AreEqual("brown", thingMap[3, 4]);
      Assert.AreEqual(string.Empty, thingMap[3, 6]);
    
      thingMap.DefaultGeneration = (k1, k2) => (k1.ToString() + k2.ToString());
    
      Assert.IsFalse(thingMap.ContainsKey(3, 6));
      Assert.AreEqual("36", thingMap[3, 6]);
      Assert.IsTrue(thingMap.ContainsKey(3, 6));
    }
    

提交回复
热议问题