我意识到我没有提供足够的信息让大多数人读懂我的想法并理解我的所有需求,所以我对原来的内容进行了一些更改。
假设我有一个类的项目列表,如下所示:
public class Thing
{
int Foo;
int Bar;
string Baz;
}
我想根据 Foo 的值对 Baz 字符串进行分类,然后是 Bar。 Foo 和 Bar 值的每种可能组合最多有一个 Thing,但我不能保证每个组合都有一个值。将其概念化为表格的单元格信息可能会有所帮助:Foo 是行号,Bar 是列号,Baz 是在那里找到的值,但不一定每个单元格都存在一个值。
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# 已经足够长的时间了,我已经习惯了为所有类似的常见问题寻找简单的单行解决方案,但这一个让我难住了。
这是使用 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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)