HomeSearch

C# Single Method: Get Element If Only One Matches

Use the Single extension from System.Linq: get an element if only one match is found.
Single. This method searches for single instances. It is found in System.Linq. With it, we search a collection for a single instance of an element matching a condition. If the collection has any number other than one element, we get an exception.SingleOrDefaultLINQ
Example. This program creates an array of 5 ints. Only one of the elements is greater than 999. Next, Single is called with a Predicate lambda expression. After this, the parameterless Single method is called on an array with only one element.Predicate

And: The Single method, when only one match is found, returns that one element.

C# program that uses Single method using System; using System.Linq; class Program { static void Main() { // Find only element > 999. int[] array1 = { 1, 3, 1000, 4, 5 }; int value1 = array1.Single(element => element > 999); // Ensure only one element. int[] array2 = { 4 }; int value2 = array2.Single(); Console.WriteLine(value1); Console.WriteLine(value2); // See exception when more than one element found. try { int value3 = array1.Single(element => element > 0); } catch (Exception ex) { Console.WriteLine(ex.GetType()); } } } Output 1000 4 System.InvalidOperationException
What happens if no single matching element is found? The program shows the Single method in a failure case. It tries to find a Single matching the predicate of > 0. There are five matching elements, so an exception is thrown.

Note: The type of the exception is System.InvalidOperationException. This exception is used throughout the .NET Framework.

Discussion. Is Single a useful method? Unfortunately, methods that can throw an exception in a normal circumstance such as Single may be less useful. Perhaps the Single method is best used as a runtime assert.

So: If your program must have a single instance of a certain element, then it can be used to alert you to serious errors.

However, in normal programs where there may be more than a single element, the exception will cause serious performance degradation. Your code could probably be clearer if written in another way.
Summary. The Single method provides a way to ensure there is a single element matching a condition. If no condition is required, the method ensures that the source collection has only one element.

Caution: This method is not useful in all programs that need to determine if a single element exists because of its exception behavior.

Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.