使用C# Except方法获取List差异结果异常的问题求助
问题原因
默认情况下,Except方法对引用类型(比如你自定义的Participants类)是按对象的引用地址比较,而不是按属性值判断相等。你代码里的vm1和vm3是两个独立的对象实例,哪怕所有属性完全一致,它们的内存地址也不一样,所以Except会把vm3判定为和Participants1里的元素不同的项,最终返回CustomerId为2和1的两个元素,和你的预期不符。
解决方案
这里提供三种实用的解决方式,按需选择:
方式一:重写Participants的相等判断方法
让类自己定义“相等”的规则,比如基于CustomerId来判断两个对象是否一致:
public class Participants { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public override bool Equals(object obj) { if (obj is Participants other) { // 可根据需求调整判断逻辑,比如加上FirstName/LastName return CustomerId == other.CustomerId; } return false; } public override int GetHashCode() { // 和Equals逻辑对应,用CustomerId生成哈希值 return CustomerId.GetHashCode(); } }
修改后再运行原代码,Except就会按照CustomerId判断相等,只返回CustomerId为2的元素。
方式二:传入自定义比较器给Except
如果不想修改Participants类,可以单独写一个比较器,传给Except的重载方法:
public class ParticipantsComparer : IEqualityComparer<Participants> { public bool Equals(Participants x, Participants y) { if (x == null || y == null) return x == y; return x.CustomerId == y.CustomerId; } public int GetHashCode(Participants obj) { return obj.CustomerId.GetHashCode(); } }
然后修改调用Except的代码:
var inFirstOnly = Participants2.Except(Participants1, new ParticipantsComparer());
方式三:用LINQ手动筛选
这种方式不需要修改类或创建比较器,直接用LINQ组合查询实现:
var inFirstOnly = Participants2.Where(p2 => !Participants1.Any(p1 => p1.CustomerId == p2.CustomerId));
逻辑很直白:筛选出Participants2中所有CustomerId不在Participants1里的元素,结果就是你要的CustomerId为2的项。
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

