【发布时间】:2009-12-17 00:25:51
【问题描述】:
我意识到我没有提供足够的信息让大多数人读懂我的想法并理解我的所有需求,所以我在原来的基础上做了一些改动。
假设我有一个这样的类的项目列表:
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# 的时间已经够长了,以至于我已经习惯于为所有此类常见问题寻找简单的单行解决方案,但这个解决方案让我很困惑。
【问题讨论】:
-
起点是什么? Thing 对象列表?
-
感谢您到目前为止的回答。我已经更新了问题以使其更清楚。看起来你们中的一些人已经有了正确的想法。测试完您的答案后,我将开始投票并分配获胜者。