C# 两个列表相交将导致一个空列表
我有两张单子C# 两个列表相交将导致一个空列表,c#,linq,intersect,C#,Linq,Intersect,我有两张单子 List<clsEntity> usersWithNPIRCodingPermission // It has count 159 List<clsEntity> usersWithRaiseReq // It has count 219 List usersWithNPIRCodingPermission//它有计数159 列出usersWithRaiseReq//它的计数为219 当在这些上进行交叉时(有55条记录,但我的下一行得到的是空列表) Li
List<clsEntity> usersWithNPIRCodingPermission // It has count 159
List<clsEntity> usersWithRaiseReq // It has count 219
List usersWithNPIRCodingPermission//它有计数159
列出usersWithRaiseReq//它的计数为219
当在这些上进行交叉时(有55条记录,但我的下一行得到的是空列表)
List users=usersWithRaiseReq.Intersect(usersWithNPIRCodingPermission.ToList();
为什么生成的
用户
列表为空?如果类型不是基元,则需要为类型实现相等比较器,例如int
等
public class UsersComparer : IEqualityComparer<clsEntity>
{
public bool Equals(clsEntity x, clsEntity y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.ID == y.ID; // or whatever you use to determine equality
}
public int GetHashCode(clsEntity x)
{
if (Object.ReferenceEquals(x, null)) return 0;
return x.ID.GetHashCode();
}
}
公共类用户比较者:IEqualityComparer
{
公共布尔等于(clsEntity x,clsEntity y)
{
if(Object.ReferenceEquals(x,y))返回true;
if(Object.ReferenceEquals(x,null)| | Object.ReferenceEquals(y,null))
返回false;
返回x.ID==y.ID;//或用于确定相等性的任何值
}
public int GetHashCode(clsEntity x)
{
if(Object.ReferenceEquals(x,null))返回0;
返回x.ID.GetHashCode();
}
}
用法:
List<clsEntity> users = usersWithRaiseReq.Except(
usersWithNPIRCodingPermissionn, new UsersComparer()).ToList();
List users=usersWithRaiseReq.Except(
usersWithNPIRCodingPermissionn,新用户comparer()).ToList();
这真的是正确的代码吗?您正在谈论intersect,但您使用的是Except
方法,而不是intersect
。clsEntity
是否实现IEquatable
?如果不是,则只对每个元素进行ReferenceEquals
。你一定要发一个帖子,这样我们才能提供帮助。额外的60个实例只是列表中其他实例的重复吗?同样是Intersec,除了使用Equalitycomparison。因此,如果有多个相等的元素,则不能依靠列表计数来验证结果。Intersect()
和Except()
使用Equals()
和GetHashCode()
,因此请确保正确实现这些元素,或执行<代码>均衡器比较器>代码,并将其交给<代码>交叉> <代码> >代码>作为参数。这工作了…现在它得到两个列表的交叉点…谢谢你的帮助如果这回答了你的问题考虑一下一旦我得到了15个名声我会把它标记为答案因为它现在不允许我标记…谢谢再次感谢你的帮助
List<clsEntity> users = usersWithRaiseReq.Except(
usersWithNPIRCodingPermissionn, new UsersComparer()).ToList();