优雅的方式来创建在C#中的嵌套词典 [英] Elegant way to create a nested Dictionary in C#

查看:80
本文介绍了优雅的方式来创建在C#中的嵌套词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到,我并没有提供足够的信息让大多数人读懂我的心思,了解我所有的需求,所以我从原来的改变这个有点。

说我有一类的物品,如这个列表:

Say I've got a list of items of a class like this:

public class Thing
{
    int Foo;
    int Bar;
    string Baz;
}

和我想根据富的值来分类的巴兹字符串,则酒吧。将有Foo和Bar值的每个可能的组合,最多的一件事,但我不能保证对每一个值。它可以帮助概念化为表的小区信息:foo是行号,酒吧是列数,巴兹是在那里找到的价值,但不一定是本作的每一个细胞值<。 / p>

And I want to categorize the Baz string based on the values of Foo, then Bar. There will be at most one Thing for each possible combination of Foo and Bar values, but I'm not guaranteed to have a value for each one. It may help to conceptualize it as cell information for a table: Foo is the row number, Bar is the column number, and Baz is the value to be found there, but there won't necessarily be a value present for every cell.

IEnumerable<Thing> things = GetThings();
List<int> foos = GetAllFoos();
List<int> bars = GetAllBars();
Dictionary<int, Dictionary<int, string>> dict = // what do I put here?
foreach(int foo in foos)
{
    // I may have code here to do something for each foo...
    foreach(int bar in bars)
    {
        // I may have code here to do something for each bar...
        if (dict.ContainsKey(foo) && dict[foo].ContainsKey(bar))
        {
            // I want to have O(1) lookups
            string baz = dict[foo][bar];
            // I may have code here to do something with the baz.
        }
    }
}



什么是容易的,优雅的方式生成嵌套的字典吗?我已经使用C#足够长的时间,我已经习惯了所有的这样的东西,共同寻找简单,一个在线解决方案,但是这一次有我难住了。

What's an easy, elegant way to generate the nested dictionary? I've been using C# long enough that I'm getting used to finding simple, one-line solutions for all of the common stuff like this, but this one has me stumped.

推荐答案

下面是使用LINQ的解决方案:

Here's a solution using Linq:

Dictionary<int, Dictionary<int, string>> dict = things
    .GroupBy(thing => thing.Foo)
    .ToDictionary(fooGroup => fooGroup.Key,
                  fooGroup => fooGroup.ToDictionary(thing => thing.Bar,
                                                    thing => thing.Baz));

这篇关于优雅的方式来创建在C#中的嵌套词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆