.NET API Documentation

Enumerable.Except Method

public static System.Collections.Generic.IEnumerable<TSource> Except<TSource>( this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second )

Computes the set difference of two sequences. This method returns elements in the first sequence that do not appear in the second sequence.

The Except method performs an order-preserving, set difference operation on two sequences. It returns only the elements from the first sequence that do not exist in the second sequence. The comparison is done using the default equality comparer for the type of the elements.

Parameters

Type Parameters

TSource: The type of the elements of the input sequences.

Return Value

An IEnumerable<TSource> that contains the elements from the first sequence that do not appear in the second sequence.

Example

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { var numbersA = new List<int> { 1, 2, 3, 4, 5 }; var numbersB = new List<int> { 4, 5, 6, 7, 8 }; var difference = numbersA.Except(numbersB); Console.WriteLine("Elements in numbersA but not in numbersB:"); foreach (var number in difference) { Console.WriteLine(number); } // Output: // 1 // 2 // 3 } }

See Also