Elegant way to create a nested Dictionary in C#

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

    Another approach would be to key your dictionary using an anonymous type based on both the Foo and Bar values.

    var things = new List
                     {
                         new Thing {Foo = 3, Bar = 4, Baz = "quick"},
                         new Thing {Foo = 3, Bar = 8, Baz = "brown"},
                         new Thing {Foo = 6, Bar = 4, Baz = "fox"},
                         new Thing {Foo = 6, Bar = 8, Baz = "jumps"}
                     };
    var dict = things.ToDictionary(thing => new {thing.Foo, thing.Bar},
                                   thing => thing.Baz);
    var baz = dict[new {Foo = 3, Bar = 4}];
    

    This effectively flattens your hierarchy into a single dictionary. Note that this dictionary cannot be exposed externally since it is based on an anonymous type.

    If the Foo and Bar value combination isn't unique in your original collection, then you would need to group them first.

    var dict = things
        .GroupBy(thing => new {thing.Foo, thing.Bar})
        .ToDictionary(group => group.Key,
                      group => group.Select(thing => thing.Baz));
    var bazes = dict[new {Foo = 3, Bar = 4}];
    foreach (var baz in bazes)
    {
        //...
    }
    

提交回复
热议问题