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.
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.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 11, 2021 (image).