System.Linq.Enumerable
Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)
Returns distinct elements in the first sequence which are not in the second sequence.
Parameters | Description |
---|---|
first<TSource>IEnumerable<TSource> |
The first IEnumerable<TSource> to project. |
second<TSource>IEnumerable<TSource> |
IEnumerable<TSource> to exclude elements from. |
Returns | An IEnumerable<TSource> that contains elements from the first sequence that do not appear in the second sequence. |
---|
Remarks |
The For a query to return an error when the sequence is empty, use the |
---|
Example
The following code example demonstrates how to use the Except
method to find the difference between two sequences.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbersA = { 0, 1, 2, 3, 4, 5 };
List<int> numbersB = { 2, 3, 4, 5, 6, 7 };
// Get the numbers that are in numbersA but not in numbersB.
IEnumerable<int> differenceQuery = numbersA.Except(numbersB);
// Use a foreach loop to process the elements in the resulting collection.
foreach (int number in differenceQuery)
{
Console.WriteLine(number); // Output: 0, 1
}
}
}
Overloads
The Except
method has several overloads to accommodate different comparison needs: