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

Array type

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.

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

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

We tested Except in the C# language. 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.

Array TypesForeach Loop Examples

C#: LINQ