.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);