Home
C#
Except Method
This page was last reviewed on Jun 11, 2021.
Dot Net Perls
Except. This C# method subtracts elements from a collection. This extension method is found in the System.Linq namespace in .NET.
Shows a method
C# method info. This method subtracts all the elements in one collection from another. It can be thought of like a Subtract method.
Extension
IEnumerable
Required input, output. Let us consider for a moment the desired input and output of an "Except" method. Then we can test to see if the method results are as expected.Shows a method
Input: 1 2 3 4 Except: 1 2 5 Result: 3 4
Example code. To start, this C# program declares two integer arrays. The second array contains 2 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
Result Here Except() returns a collection where the second array's elements are subtracted from the first.
Detail No errors occur when Except() is called and some of the elements in the second collection are not found in the first collection.
And The elements are ignored in the computation. Except() is not useful for validating that one collection is contained within another.
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); } } }
3 4
A discussion. Often, methods like Except are not as easy to understand as other approaches. When developing programs, the clearest approach is often best.
Detail We can use a looping construct like "for" to implement the functionality of Except.
And A loop takes more code, and is not as impressive to read, but may be easier for other developers to understand.
Summary. The Except extension method provides a fast way to use set logic. It removes all the elements from one IEnumerable that are found in another.
Array
foreach
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 11, 2021 (image).
Home
Changes
© 2007-2024 Sam Allen.