C# Single

LINQ: language integrated query

Single 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.

Example

One: 1

This program creates an array of five 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.

PredicateLambda Expression

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

Program that uses Single method: C#

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
Warning: exclamation mark

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

Question and answer

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.


C#: LINQ