Intersect扩展方法需要两个集合。它返回一个新集合,其中包含两个集合中都存在的公共元素。看下面的实例。
IList<string> strList1 = new List<string>() { "One", "Two", "Three", "Four", "Five" }; IList<string> strList2 = new List<string>() { "Four", "Five", "Six", "Seven", "Eight"}; var result = strList1.Intersect(strList2); foreach(string str in result) Console.WriteLine(str);
Four Five
Intersect 扩展方法不返回复杂类型集合的正确结果。为了从 Intersect 方法中得到正确的结果,需要实现 IEqualityComparer 接口。
为 Student 类实现 IEqualityComparer 接口,如下所示:
public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public int Age { get; set; } } class StudentComparer : IEqualityComparer<Student> { public bool Equals(Student x, Student y) { if (x.StudentID == y.StudentID && x.StudentName.ToLower() == y.StudentName.ToLower()) return true; return false; } public int GetHashCode(Student obj) { return obj.StudentID.GetHashCode(); } }
现在,您可以在Intersect扩展方法中通过StudentComparer类,以获取正确的结果:
示例:C#中的Intersect运算符
IList<Student> studentList1 = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; IList<Student> studentList2 = new List<Student>() { new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; var resultedCol = studentList1.Intersect(studentList2, new StudentComparer()); foreach(Student std in resultedCol) Console.WriteLine(std.StudentName);
Bill Ron