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

如何对Dictionary<string, List<int>>按整数值分组并筛选?

实现Dictionary按值列表中的整数分组筛选

给定一个键为string、值为List<int>的Dictionary<string, List<int>>,要基于整数值分组并筛选,最终输出Dictionary<int, List<string>>类型的结果(比如筛选值为2时,键2对应包含"LD010101"和"LD030101"的列表),可以通过以下方式实现:

完整代码示例

// 初始化原字典
Dictionary<string, List<int>> check2 = new Dictionary<string, List<int>>();     
check2.Add("LD010101", new List<int> { 1, 2, 3 });
check2.Add("LD010201", new List<int> { 1 });
check2.Add("LD030101", new List<int> { 2, 3, 4 });
check2.Add("LD030201", new List<int> { 1, 3, 4 });
check2.Add("LD040101", new List<int> { 5, 1, 4 });
check2.Add("LD050101", new List<int> { 1, 3, 4 });

// 1. 生成包含所有整数分组的目标字典
Dictionary<int, List<string>> fullResult = check2
    // 展开键值对:将每个整数与对应的字符串键关联
    .SelectMany(kv => kv.Value.Select(num => new { Num = num, Key = kv.Key }))
    // 按整数值分组
    .GroupBy(item => item.Num)
    // 转换为目标字典
    .ToDictionary(g => g.Key, g => g.Select(item => item.Key).ToList());

// 2. 仅筛选特定整数值(示例:筛选值为2)
int targetNumber = 2;
Dictionary<int, List<string>> filteredResult = check2
    .SelectMany(kv => kv.Value.Select(num => new { Num = num, Key = kv.Key }))
    // 过滤出目标整数
    .Where(item => item.Num == targetNumber)
    .GroupBy(item => item.Num)
    .ToDictionary(g => g.Key, g => g.Select(item => item.Key).ToList());

代码说明

  • SelectMany:将原字典中每个值列表的整数拆分为独立条目,与对应的字符串键组成匿名对象,把一对多的嵌套结构转为扁平的一对一结构。
  • GroupBy:以整数值为分组依据,将所有关联的字符串键归为一组。
  • ToDictionary:将分组结果转换为目标类型的字典,键为整数值,值为该整数对应的所有字符串键列表。

执行筛选值为2的代码后,filteredResult的结果为:

key:2, Value: {"LD010101","LD030101"}

内容的提问来源于stack exchange,提问作者sst

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:51:13