比对两个List中的数据 1 ListListA= new List () 2 { 3 new Person(){ SerialNumber = "1", AccountNumber = "111"}, 4 new Person(){ SerialNumber = "2", AccountNumber = "222"}, 5 new Person(){ SerialNumber = "3", AccountNumber = "333"}, 6 new Person(){ SerialNumber = "4", AccountNumber = "444"}, 7 new Person(){ SerialNumber = "5", AccountNumber = "555"}, 8 }; 9 List ListB = new List ()10 {11 new Person(){ SerialNumber = "1", AccountNumber = "111"},12 new Person(){ SerialNumber = "5", AccountNumber = "BBB555"}, 13 new Person(){ SerialNumber = "333", AccountNumber = "333"},14 new Person(){ SerialNumber = "2", AccountNumber = "BB222"},15 new Person(){ SerialNumber = "444", AccountNumber = "BBB444"}, 16 };17 18 //ListA中存在 ListB不存在19 var result1 = ListA.Union(ListB, new MyComparer())20 .Except(ListB, new MyComparer())21 .Cast ().ToList(); 22 //ListA中不存在 ListB存在23 var result2 = ListA.Union(ListB, new MyComparer())24 .Except(GapExpenseList, new MyComparer())25 .Cast ().ToList();26 //ListA和ListB都存在 ListA的数据27 var result3 = ListA.Intersect(ListB, new MyComparer()).Cast ().ToList();29 30 //ListA和ListB都存在 ListB的数据31 var result4 = ListB.Intersect(ListA, new MyComparer()).Cast ().ToList();
再写一个Compare类
1 public class MyComparer : IEqualityComparer2 { 3 public bool Equals(ExceptionCompare x, ExceptionCompare y) 4 { 5 return x.SerialNumber == y.SerialNumber; 6 } 7 8 public int GetHashCode(ExceptionCompare obj) 9 {10 return obj.SerialNumber.GetHashCode();11 } 12 }