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

How to handle data from nested dictionary in C#

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

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

"TClassType"包含三个属性:

我给这个嵌套结构添加值如下:

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] 条目,我想获取与此相关的所有相关键和值嵌套字典中的外键。

抱歉,我希望这不会造成混淆,我发现提出这个问题和尝试实施一样困难。

提前谢谢大家

试试这个:

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

你以前用过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();