Elegant way to create a nested Dictionary in C#

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

    I think the simplest approach would be to use the LINQ extension methods. Obviously I haven't tested this code for performace.

    var items = new[] {
      new Thing { Foo = 1, Bar = 3, Baz = "a" },
      new Thing { Foo = 1, Bar = 3, Baz = "b" },
      new Thing { Foo = 1, Bar = 4, Baz = "c" },
      new Thing { Foo = 2, Bar = 4, Baz = "d" },
      new Thing { Foo = 2, Bar = 5, Baz = "e" },
      new Thing { Foo = 2, Bar = 5, Baz = "f" }
    };
    
    var q = items
      .ToLookup(i => i.Foo) // first key
      .ToDictionary(
        i => i.Key, 
        i => i.ToLookup(
          j => j.Bar,       // second key
          j => j.Baz));     // value
    
    foreach (var foo in q) {
      Console.WriteLine("{0}: ", foo.Key);
      foreach (var bar in foo.Value) {
        Console.WriteLine("  {0}: ", bar.Key);
        foreach (var baz in bar) {
          Console.WriteLine("    {0}", baz.ToUpper());
        }
      }
    }
    
    Console.ReadLine();
    

    Output:

    1:
      3:
        A
        B
      4:
        C
    2:
      4:
        D
      5:
        E
        F
    

提交回复
热议问题