如何从List<Dictionary<string, string>>中筛选去重后的指定元素
解决方案
没问题,我来帮你搞定这个需求!核心就是两步:先基于labelGroup和idtGroupe的组合去重,再移除每个字典里的variables键。下面给你两种实用的C#实现方式:
方法1:用DistinctBy(.NET Core 3.0+/ .NET 5+ 推荐)
DistinctBy是LINQ的扩展方法,能直接指定去重的判断依据,代码更简洁直观:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // 你的原始测试列表 List<Dictionary<string, string>> test = new List<Dictionary<string, string>> { new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}}, new Dictionary<string, string>{{"labelGroup", "Livret B"}, {"idtGroupe", "idtLivretB"}, {"variables", "test2"}}, new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}}, // ... 其他重复条目 }; // 核心处理逻辑 var result = test // 按labelGroup+idtGroupe的组合去重 .DistinctBy(dict => new { Label = dict["labelGroup"], Id = dict["idtGroupe"] }) // 生成不含variables键的新字典 .Select(dict => dict.Where(kv => kv.Key != "variables").ToDictionary(kv => kv.Key, kv => kv.Value)) .ToList(); // 验证输出 foreach (var item in result) { Console.WriteLine($"labelGroup: {item["labelGroup"]}, idtGroupe: {item["idtGroupe"]}"); } } }
方法2:用GroupBy(兼容旧版.NET Framework)
如果你的项目基于.NET Framework 4.x这类没有DistinctBy的环境,用GroupBy也能实现相同效果:
var result = test // 按labelGroup+idtGroupe分组,把重复项归为一组 .GroupBy(dict => new { Label = dict["labelGroup"], Id = dict["idtGroupe"] }) // 取每个分组的第一个元素(因为组内都是重复项) .Select(g => g.First()) // 过滤掉variables键,生成新字典 .Select(dict => dict.Where(kv => kv.Key != "variables").ToDictionary(kv => kv.Key, kv => kv.Value)) .ToList();
关键说明
- 去重逻辑:用匿名类型
new { Label = dict["labelGroup"], Id = dict["idtGroupe"] }作为判断重复的依据,确保只有这两个键完全匹配的条目才会被合并。 - 移除
variables键:通过Where过滤掉目标键,再用ToDictionary生成新字典,不会修改原始数据,更安全。
运行后你会得到两个去重后的字典:
{"labelGroup": "Livret A", "idtGroupe": "idtLivretA"}{"labelGroup": "Livret B", "idtGroupe": "idtLivretB"}
内容的提问来源于stack exchange,提问作者mehdi bennie
相关产品推荐
相关产品推荐

