C# Except Extension

LINQ (language integrated query)

Except subtracts elements from a collection. This extension method is found in the System.Linq namespace in the .NET Framework. It essentially subtracts all the elements in one collection from another.

Example

Note

To start, this program uses two integer arrays. The second array contains two of the same elements as the first. Next, when the Except method is called upon the first array with the second array as the argument, the result is a collection where the second array's elements are subtracted from the first.

This C# example uses the Except method. Except is found in System.Linq.

Program that calls Except method [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Contains four values.
	int[] values1 = { 1, 2, 3, 4 };

	// Contains three values (1 and 2 also found in values1).
	int[] values2 = { 1, 2, 5 };

	// Remove all values2 from values1.
	var result = values1.Except(values2);

	// Show.
	foreach (var element in result)
	{
	    Console.WriteLine(element);
	}
    }
}

Output

3
4
Question and answer

What about elements not found? No errors occur when Except is called and some of the elements in the second collection are not found in the first collection. The elements are ignored in the computation.

Summary

The Except extension method provides a fast way to use set logic to remove all the elements from one array that are found in another array. This can reduce the need for developing complex foreach loops using imperative control.

LINQ Examples
.NET