如何在 C# 中使用 LINQ 过滤嵌套字典?
Posted
技术标签:
【中文标题】如何在 C# 中使用 LINQ 过滤嵌套字典?【英文标题】:How can I filter a nested dictionary using LINQ in C#? 【发布时间】:2021-06-22 18:49:13 【问题描述】:这是我开始使用的字典:
Dictionary<string, Dictionary<string, string>> countriesByContinentDictionary = new Dictionary<string, Dictionary<string, string>>
"Europe",
new Dictionary<string, string>
"0", "France" ,
"1", "Germany",
"2", "Switzerland"
,
"Asia",
new Dictionary<string, string>
"zero", "India" ,
"1", "Pakistan" ,
"2", "Russia"
,
"Africa",
new Dictionary<string, string>
"0", "South Africa" ,
"1", "Nigeria" ,
"2", "Lybia"
;
我正在尝试过滤到具有字母 r 的国家/地区。 这就是我试图让它看起来像过滤后的样子:
Dictionary<string, Dictionary<string, string>> countriesByContinentDictionary = new Dictionary<string, Dictionary<string, string>>
"Europe",
new Dictionary<string, string>
"0", "France" ,
"1", "Germany",
"2", "Switzerland"
,
"Asia",
new Dictionary<string, string>
,
"Africa",
new Dictionary<string, string>
"0", "South Africa" ,
"1", "Nigeria"
;
这是我目前的代码:
public static Dictionary<string, Dictionary<string, string>> GetRecordsContainingSubStringWithLambda(Dictionary<string, Dictionary<string, string>> originalNestedDictionary, string lambdaSubString)
var filteredNestedDictionary = Enumerable.Range(0, originalNestedDictionary.Count)
.Select(
row => Enumerable.Range(0, originalNestedDictionary.ElementAt(row).Value.Count)
.Select(col => originalNestedDictionary.ElementAt(row).Value.ElementAt(col))
.Where(keyValuePair => keyValuePair.Value != null && keyValuePair.Value.Contains(lambdaSubString))
.ToDictionary<string, string>(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value)
).ToDictionary<string, Dictionary<string, string>>(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value);
return filteredNestedDictionary;
但我收到以下错误:
error CS0029: Cannot implicitly convert type 'System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<string, string>, string>' to 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>'
【问题讨论】:
【参考方案1】:注意Dictionary<TKey, TValue>
直接实现了IEnumerable<KeyValuePair<TKey, TValue>>
,所以我们不需要计算索引。相反,使用Select
转换外部字典中的每个项目,并使用Where
过滤掉与过滤器不匹配的内部项目,如下所示:
public static Dictionary<string, Dictionary<string, string>> GetRecordsContainingSubStringWithLambda(Dictionary<string, Dictionary<string, string>> originalNestedDictionary, string lambdaSubString)
return originalNestedDictionary.Select(outerPair => new KeyValuePair<string, Dictionary<string, string>>(
outerPair.Key,
outerPair.Value
.Where(innerPair => innerPair.Value != null && innerPair.Value.Contains(lambdaSubString))
.ToDictionary(innerPair => innerPair.Key, innerPair => innerPair.Value)
)).ToDictionary(outerPair => outerPair.Key, outerPair => outerPair.Value);
【讨论】:
感谢您的回答。这行得通。我通过将innerPair.Key
替换为innerPair.Value
进行了一项更改,以检查该值是否为null
。如果innerPair.Value
是null
,我会收到错误消息。
@j.ruiz 啊,是的,那是我的错字。我会编辑答案:)以上是关于如何在 C# 中使用 LINQ 过滤嵌套字典?的主要内容,如果未能解决你的问题,请参考以下文章