C # Two collections compare difference values for the except of a value type of LINQ
List<string> strList1 = new List<string>(){"a", "b", "c", "d"}; List<string> strList2 = new List<string>() { "a", "b", "f", "e"}; var strList3 = strList1.Except(strList2).ToList(); for (int i = 0; i < strList3.Count; i++) { Console.WriteLine(strList3[i]); }
The result of the output is C D
var strList3 = strlist1.except (strList2). ToList ();
This means that the strList1 is not in the strList2, and the obtained difference is stored in the StrList3 (ie: strList1, strList2)
var strList3 = strlist2.except (strList1). ToList ();
So the result of the output is F E
Here will strList1 and strList2 position swap, is strList2 in which is not strList1 in StrList3 (ie: strList2, strList1)
Collection comparison difference for reference types
First create the Student class
public class Student { public int Id { get; set; } public string Name { get; set; } }
Then create a list of 2
List<Student> studentList1=new List<Student>() { new Student(){Id = 1,Name = "小明"}, new Student(){Id = 2,Name = "小刚"}, new Student(){Id = 3,Name = "小红"}, }; List<Student> studentList2 = new List<Student>() { new Student(){Id = 1,Name = "小明"} }; var studentList3 = studentList1.Except(studentList2).ToList(); for (int i = 0; i < studentList3.Count; i++) { Console.WriteLine($"学号: {studentList3[i].Id} 姓名: {studentList3[i].Name}"); }
Result output
学号: 1 姓名: 小明学号: 2 姓名: 小刚学号: 3 姓名: 小红
This is because except generates a difference of two sequences by using the default equality comparer to compare values, and the Equals and GetHashCode methods need to be rewritten
As follows:
- Method One
public class Student { public int Id { get; set; } public string Name { get; set; } public override bool Equals(object obj) { if (obj is Student) { Student student = obj as Student; return Id == student.Id && Name == student.Name; } return false; } public override int GetHashCode() { return Id.GetHashCode() ^ Name.GetHashCode(); } }
- Method two overrides a class to let it inherit IEqualityComparer
public class StudentComparer: IEqualityComparer<Student> { public bool Equals(Student x, Student y) { return x.Id == y.Id && x.Name == y.Name; } public int GetHashCode(Student obj) { return obj.Id.GetHashCode() ^ obj.Name.GetHashCode(); } }
Special attention
var studentList3 = studentList1.Except(studentList2,new StudentComparer()).ToList();
We need to add the parameter new Studentcomparer ()
C # Two collection comparison of the usage of the except of the Difference LINQ