# List Except 操作，IEqualityComparer 使用

1.此接口用于对集合 的自定义相等比较算法的实现。包含2个方法：

• Equals(T,T): 确定指定的对象是否相等。 T 为要比较的对象类型；
• GetHashCode(T) :返回指定对象的哈希代码。如果两个对象的Equal
比较结果相等，则他们hashCode返回的对象也必须返回同一个值；

2.官方建议继承 EqualityComparer<T> 而不是实现 IEqualityComparer<T>

3.

Union()

public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)

public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first,IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)

Intersect ()

public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)

public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, Enumerable<TSource> second,IEqualityComparer<TSource> comparer)


Except ()

public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
class Program
{
static void Main(string[] args)
{
IList<Student> oneStudents = new List<Student>();

IList<Student> twoStudents = new List<Student>();

IList<Student> threeStudents = new List<Student>();
var bingji = oneStudents.Union(twoStudents, new StudentListEquality()).ToList();//并（全）集
var jiaoji = oneStudents.Intersect(threeStudents, new StudentListEquality()).ToList();//交集
var chaji = oneStudents.Except(threeStudents, new StudentListEquality()).ToList();//差集

Console.WriteLine();
Console.WriteLine("以下是并集的结果");
bingji.ForEach(x =>
{
Console.WriteLine(x.StudentId.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());

});
Console.WriteLine();
Console.WriteLine("以下是交集的结果");
jiaoji.ForEach(x =>
{
Console.WriteLine(x.StudentId.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());

});

Console.WriteLine();
Console.WriteLine("以下是差集的结果");
chaji.ForEach(x =>
{
Console.WriteLine(x.StudentId.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());

});

}

}

public class Student
{
public Student(int studentId, bool sex, String name, String address)
{
this.StudentId = studentId;
this.Sex = sex;
this.Name = name;
}
public int StudentId { get; set; }
public bool Sex { get; set; }
public String Name { get; set; }
public String Address { get; set; }

}
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();
}
}
}

}


https://msdn.microsoft.com/zh-cn/library/bb336390(v=vs.110).aspx

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120