.net找List1和List2的差集

有个需求是找两个自定义类泛型集合的差集:

class Person

{

  public string Name{get; set;}

  public string Country{get; set;}

}

判断依据仅仅是Name是否相同,于是重写该类的Equals和GetHashCode方法:

class Person
{
  public string Name{get; set;}
  public string Country{get; set;}

  public override bool Equals(object obj)
  {
       bool equal = false;
       UrlImg p = obj as UrlImg;
       if (p != null)
       {
           equal = this.Name== p.Name;
       }
       return equal;
  }

   public override int GetHashCode()
   {
       return this.Name.GetHashCode();
   }
}

 

原本Equals是比较地址值的,哪怕两个对象值完全相同但地址不同也是false,现在需求是只看Name,因此重写后就达到要求了,然后使用linq自带的List.Except(List)方法就行了:

List<Person> exceptList = list1.Except(list2);

 

posted on 2014-12-11 15:37  邓绍俊  阅读(626)  评论(0编辑  收藏  举报

导航