List求交并补集--IEqualityComparer实现

 

问题:

  

两个List<Student>,求交、并、补集。

 

解决办法:

用直接调用List里面的现成方法来解决,不过当数据量大的时候,这时不可行的。anyway,先看这个吧(以求交集为例)。

实现IEqualityComparer接口
public class StudentListEquality : IEqualityComparer<Student>
   {
       public bool Equals(Student x, Student y)
       {
           return x.StudentId == y.StudentId;
       }

       public int GetHashCode(Student obj)
       {
           if (obj == null)
           {
               return 0;
           }
           else
           {
                return obj.ToString() .GetHashCode();
           }
       }
   }
调用Intersect方法
List<Student> oldStudentList={...};
List<Student> newStudentList={...};
 
List<Student>studnetsCommon=oldStudentList.Intersect(
              newStudentList, new StudentListEquality()).ToList();

 

原因:

     C#中,求两个List的交集/并集/补集,可以调用List类中的Intersect,Union和Except方法,但是它会要去你提供指定的等值比较器,也就是自己实现IEqualityComparer接口。当然如果没有提供,则是按照默认的比较器来判断,结果可能会与你的初衷相悖。
    等值比较器是根据自己的需求写的。上面的代码中实现了IEqualityCompare接口,用来判断两个student是否是同一个。但我只是写了根据StudentId是否相同来判断,当然也可以传递参数,指定具体比较对象的哪个属性。 这就需要用到枚举类型了,详细可以参看我的另外一篇:List<>根据指定属性排序(实现IComparer接口)

 

posted @ 2012-08-25 12:44  阿凡迪  阅读(980)  评论(0编辑  收藏  举报