Except()方法需要两个集合。它返回一个新集合,其中包含来自第一个集合的元素,该元素在第二个集合(参数集合)中不存在。
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.Except(strList2); foreach(string str in result) Console.WriteLine(str);
One Two Three
Except扩展方法不返回复杂类型集合的正确结果。您需要实现IEqualityComparer接口,以便从Except方法获得正确的结果。
为 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(); } }
现在,您可以在Except扩展方法中通过StudentComparer类,以获取正确的结果:
示例:C#对象类型为的Except()方法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.Except(studentList2,new StudentComparer()); foreach(Student std in resultedCol) Console.WriteLine(std.StudentName);
John Steve
C # & VB.Net 查询语法不支持 Except 运算符。但是,您可以对查询变量使用 Distinct 方法,或者将整个查询包装到括号中,然后调用 Except ()。