如何在C#中按相同Parent和Child属性值分组List<DepartmentSchema>
解决按Parent+Child组合去重的LINQ方案
嘿,我懂你要的是把列表里重复的(Parent, Child)配对彻底去掉,只保留每一组唯一的组合对吧?你提到已经尝试用IGrouping相关的方法,那我给你几个实用的LINQ实现方案,直接就能用:
方案1:用GroupBy(兼容所有.NET版本)
这应该是你之前尝试的方向,核心是把Parent和Child的组合作为分组键,然后从每个分组里取任意一个元素(因为同一组里的元素都是重复的)。这里用匿名类型当分组键最方便,因为C#的匿名类型会自动基于属性值生成Equals和GetHashCode方法,能准确识别相同的配对。
List<DepartmentSchema> originalList = /* 你的原始集合 */; var uniqueDepartments = originalList .GroupBy(d => new { d.Parent, d.Child }) // 按Parent+Child组合分组 .Select(g => g.First()) // 取每组第一个元素(或者g.Last()都可以) .ToList();
方案2:用DistinctBy(.NET 6+ 更简洁)
如果你用的是.NET 6及以上版本,DistinctBy方法能一步到位,直接指定去重的键,代码更简洁:
List<DepartmentSchema> originalList = /* 你的原始集合 */; var uniqueDepartments = originalList .DistinctBy(d => new { d.Parent, d.Child }) .ToList();
备选方案:自定义相等比较器(兼容旧版本)
如果你的项目用的是.NET Framework或者低于6的.NET Core,也可以自己实现IEqualityComparer<DepartmentSchema>,然后用Distinct方法:
public class DepartmentEqualityComparer : IEqualityComparer<DepartmentSchema> { public bool Equals(DepartmentSchema x, DepartmentSchema y) { if (ReferenceEquals(x, y)) return true; if (x is null || y is null) return false; return x.Parent == y.Parent && x.Child == y.Child; } public int GetHashCode(DepartmentSchema obj) { return HashCode.Combine(obj.Parent, obj.Child); } } // 使用的时候: var uniqueDepartments = originalList.Distinct(new DepartmentEqualityComparer()).ToList();
不管用哪种方法,最终得到的uniqueDepartments都会是你要的结果:
| Parent | Child |
|---|---|
| 4 | 1 |
| 8 | 4 |
| 5 | 7 |
| 4 | 2 |
内容的提问来源于stack exchange,提问作者riv




