You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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)));

代码解释

  1. 外层的SelectMany遍历整个SortedDictionary<int, ...>的每个键值对(KeyValuePair<int, Dictionary<string, HashSet<long>>>)。
  2. 对于每个外层键值对,我们用Select遍历它内部的Dictionary<string, HashSet<long>>的所有键值对。
  3. 最后把外层的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:24:08