C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Note: The type of the exception is System.InvalidOperationException. This exception is used throughout the .NET Framework.
So: If your program must have a single instance of a certain element, then it can be used to alert you to serious errors.
Caution: This method is not useful in all programs that need to determine if a single element exists because of its exception behavior.