English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ Set Operator Except

The Except() method requires two collections. It returns a new collection that contains elements from the first collection that do not exist in the second collection (parameter collection).

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);
Output:
One
Two
Three

The Except extension method does not return the correct results for complex type collections. You need to implement the IEqualityComparer interface to obtain the correct results from the Except method.

To implement the IEqualityComparer interface for the Student class, as shown below:

Example: Using the Except method in C#
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();
    }
}

Now, you can get the correct result through the StudentComparer class in the Except extension method:

Example: C# object type Except() method
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);
Output:
John
Steve

C# & VB.Net query syntax does not support the Except operator. However, you can use the Distinct method on the query variable, or enclose the entire query in parentheses and then call Except().