如何使用LINQ展平SortedDictionary<int, Dictionary<string, HashSet<long>>>类型的嵌套字典
解决嵌套字典的LINQ完全展平问题
你之前的代码只完成了一半的展平工作——它把外层字典的所有内层字典拆成了KeyValuePair<string, HashSet<long>>的集合,但丢失了最外层的int类型键,也没有把三个层级的数据整合到单个元素里。要实现完全展平并保留所有层级的信息,你需要嵌套使用SelectMany和Select,把每个层级的键和值关联起来。
方法一:使用匿名类型(可读性好)
var flattened = dictionary .SelectMany(outerPair => outerPair.Value.Select(innerPair => new { OuterKey = outerPair.Key, // 最外层的int键 InnerKey = innerPair.Key, // 中间层的string键 LongSet = innerPair.Value // 最底层的HashSet<long> }));
方法二:使用值元组(更轻量,无需定义类型)
如果你用的是C# 7.0及以上版本,值元组会是更简洁的选择:
var flattened = dictionary .SelectMany(outerPair => outerPair.Value.Select(innerPair => (outerPair.Key, innerPair.Key, innerPair.Value)));
代码解释
- 外层的
SelectMany遍历整个SortedDictionary<int, ...>的每个键值对(KeyValuePair<int, Dictionary<string, HashSet<long>>>)。 - 对于每个外层键值对,我们用
Select遍历它内部的Dictionary<string, HashSet<long>>的所有键值对。 - 最后把外层的
int键、内层的string键,以及对应的HashSet<long>整合成单个元素,最终得到的就是包含这三个数据的扁平化集合。
举个简单的例子:假设你的字典结构是这样的:
var dictionary = new SortedDictionary<int, Dictionary<string, HashSet<long>>> { { 1, new Dictionary<string, HashSet<long>> { { "GroupA", new HashSet<long> { 100, 200 } }, { "GroupB", new HashSet<long> { 300 } } } }, { 2, new Dictionary<string, HashSet<long>> { { "GroupC", new HashSet<long> { 400, 500, 600 } } } } };
展平后会得到3个元素:
(OuterKey: 1, InnerKey: "GroupA", LongSet: {100,200})(OuterKey: 1, InnerKey: "GroupB", LongSet: {300})(OuterKey: 2, InnerKey: "GroupC", LongSet: {400,500,600})
内容的提问来源于stack exchange,提问作者user122222
相关产品推荐
相关产品推荐

