{TOC}
| Namespace: | System.Linq |
| Assembly: | System.Core.dll |
| Extends: | IEnumerable<T> |
Back to
Standard Query Operator IndexEditIntroduction
The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second. You can optionally provide your own equality comparison function.
EditMethod Signatures
// 1 - Returns only elements that appear in one of the sequences.
public static IEnumerable<TSource> Except<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second)
// New in January CTP
// 2 - Returns only elements that appear in one of the sequences.
// A custom function is used to determine equality.
public static IEnumerable<TSource> Except<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
IEqualityComparer<TSource> comparer)EditExceptions
Throws an ArgumentNullException if
first or
second is null
EditPseudo-code
Overload 1
If
first is null, throw an ArgumentNullException.
If
second is null, throw an ArgumentNullException.
Add all the distinct
second elements to a list (distinct element list)
Iterate the
first sequence.
If the current element is NOT in the distinct element list (as evaluated equal using EqualityComparer<TSource>.Default),
Return the current element (pick up from here when the next element is requested).
Overload 2
If
first is null, throw an ArgumentNullException.
If
second is null, throw an ArgumentNullException.
Add all the distinct
second elements to a list (distinct element list)
Iterate the
first sequence.
If the current element is NOT in the distinct element list (as evaluated by the comparer function provided for equality evaluation),
Return the current element (pick up from here when the next element is requested).
EditLoop Count
The entire
second sequence will be looped.
The
first sequence follows: This operator implements the standard
deferred execution iterator pattern. This means, no looping will occur until the result is iterated over.
EditCode Samples
This sample shows that the except operator will only return those elements in the
first sequence that are not in the
second sequence.
public static void ExceptTest() {
int[] first = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] second = new int[] { 4, 5, 6, 10 };
var q = first.Except(second);
foreach (var num in q)
Console.WriteLine(num);
Console.ReadLine();
}0
1
2
3
7
8
9