C# Except

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.

Extension Method

Example

Elements

To start, this program uses two integer arrays. The second array contains two of the same elements as the first. Next, the Except method is called upon the first array with the second array as the argument.

Int Array

And:The result is a collection where the second array's elements are subtracted from the first.

Based on:

.NET 4.5

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.

So:The Except method is not useful for validating that one collection is contained within another.

Discussion

Method

Often, methods like Except are not as easy to understand as other approaches. When developing programs, the clearest approach is often best. We can use a looping construct to implement the functionality of Except.

Arrow indicates looping

And:It takes more code, and is not as impressive to read, but may be easier for other developers to understand it.

Summary

The Except extension method provides a fast way to use set logic. It removes all the elements from one array that are found in another array. This reduces the need for complex foreach-loops.

ArrayForeach

C#: LINQ