我有2个列表< CustomClass>想比较但没有得到预期的结果 [英] I have 2 list<CustomClass> want to compare but not getting expected result

查看:73
本文介绍了我有2个列表< CustomClass>想比较但没有得到预期的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级

 

我使用此方法来制作列表 

I am usnig this method for comapring the list 

当我调试代码时,我的期望是它应该返回"不同"。列表计数为0,因为我传递相同的列表表单代码作为参数。

while I am debugging code my expectation is that it should return "differ" list count is 0 as i am passing same list form code as parameter.

这些是我的列表运行时的视图

these are the views at run time of my list

注意: - 两个列表只包含1条记录

note:-BOTH LIST Only contains 1 record

第二个列表是 

2nd List is 

请告诉我有什么不同的b / w我无法找到...... :(

please let me know what is the differences b/w which i am unable to find...:(

我尝试了很多来自google.like do intersection和union的方法,但结果是相同的,它给了我不同的数1

I tried lots of another methods from google.like do intersection and union but result are same it is giving me differ count 1

推荐答案

参考类型通过基础参考进行比较。
除了
将使用默认的比较器,除非你使用否则接受的重载。除非你将两个列表初始化为相同的对象然后你我会得到不同的对所有物品都有所了解。如果你想通过其他东西(可能是Name属性)
进行比较,那么你需要使用接受自定义比较器的重载。然后,自定义比较器可以使用Name来确定2个对象是否相等。

Ref types compare by the underlying reference. Except will use the default comparer unless you use the overload that accepts otherwise. Unless you initialized both lists to the same objects then you'd get differences for all the items. If you want to compare by something else (perhaps that Name property) then you need to use the overload that accepts a custom comparer. The custom comparer can then use Name to determine if 2 objects are equal.

class SendPortComparer : IEqualityComparer<SendPortData>
{
   public bool Equals ( SendPortData left, SendPortData right )
   {
      if (Object.ReferenceEquals(left, right))
         return true;

      if (Object.ReferenceEquals(left, null) ||
          Object.ReferenceEquals(right, null))
         return false;

      return String.Compare(left.Name, right.Name, true) == 0;
   }

   public int GetHashCode ( SendPortData data )
   {
      if (Object.ReferenceEquals(data, null))
         return 0;

      return data.Name?.GetHashCode() ?? 0;
   }
}

var differenceQuery = nonCRMSPort.Except(CRMSPort, new SendPortComparer());

Michael Taylor

http://www.michaeltaylorp3.net

Michael Taylor
http://www.michaeltaylorp3.net


这篇关于我有2个列表&lt; CustomClass&gt;想比较但没有得到预期的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆