如何在C#中处理嵌套字典中的数据

时间:2015-02-10 10:25:40

标签: c# dictionary collections

我已经设置了一个嵌套字典,如下所示:

static Dictionary<string, Dictionary<UInt32, TClassType> > m_dictionary = new Dictionary<string, Dictionary<UInt32, TClassType>>();

“TClassType”包含三个属性:

  • 标题(字符串)
  • code(uint)
  • 地址(字符串)

我为这个嵌套结构增加了值,如下所示:

TClassType newEntry = new TClassType(s_title, ui_code, s_address)
if (! m_dictionary.ContainsKey(s_title))// check as the same s_title can occur multiple times but have different ui_code and s_address values
{
    m_dictionary.Add(s_title, new Dictionary<uint, TClassType>());
}
m_dictionary[s_title].Add(ui_code, s_address);

现在我的问题是访问特定密钥[s_title]的所有值的好方法是什么?

键[s_title]将包含嵌套字典中的许多项目,对于唯一的[s_title]条目,我想从嵌套字典中获取与此外键相关的所有相关键和值。

对不起,我希望这不会令人困惑,我觉得很难问,因为我试图实施。

提前谢谢大家

2 个答案:

答案 0 :(得分:1)

试试这个:

if (m_dictionary.Contains(s_title))
    foreach(TClassType entry in m_dictionary[s_title].Values)
        // Do something with the entry.

答案 1 :(得分:1)

你以前用过linq吗?这将是groupby的主要用途。你正在做的事情会增加一定程度的卷积。

如果你有一个TClassType列表,你可以使用linq where表达式来获取那些你正在寻找的标题,然后是你需要的ui_code。

编辑例如(我在移动设备之前很难编写代码:))

IEnumerable<TClassType> entries = entriesList;//whatever you use to populate the entries
var titles = entries.Where(x=> x.s_title == "Title you're looking for").Distinct();