Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Single() Method
The Single() method in C# returns the only element of a sequence. It throws an exception if the sequence is empty or contains more than one element, making it useful when you expect exactly one element.
The Single() method is available in both LINQ to Objects and LINQ to Entities through the System.Linq namespace.
Syntax
Following is the syntax for the Single() method −
public static TSource Single<TSource>(this IEnumerable<TSource> source); public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
Parameters
source − The IEnumerable<T> to return the single element from.
predicate − A function to test each element for a condition (optional).
Return Value
Returns the single element of the input sequence, or the single element that satisfies the condition.
Using Single() with One Element
When you have a sequence with exactly one element, Single() returns that element −
using System;
using System.Linq;
public class Demo {
public static void Main() {
string[] str = { "one" };
string res = str.Single();
Console.WriteLine("Single element: " + res);
int[] numbers = { 42 };
int number = numbers.Single();
Console.WriteLine("Single number: " + number);
}
}
The output of the above code is −
Single element: one Single number: 42
Using Single() with Predicate
You can use Single() with a predicate to find the single element that matches a condition −
using System;
using System.Linq;
public class Demo {
public static void Main() {
int[] numbers = { 1, 2, 3, 4, 5 };
// Find the single even number greater than 3
int result = numbers.Single(x => x > 3 && x % 2 == 0);
Console.WriteLine("Single even number > 3: " + result);
string[] names = { "Alice", "Bob", "Charlie" };
string name = names.Single(n => n.StartsWith("B"));
Console.WriteLine("Name starting with B: " + name);
}
}
The output of the above code is −
Single even number > 3: 4 Name starting with B: Bob
Exception Handling with Single()
The Single() method throws exceptions in specific scenarios. Here's how to handle them −
using System;
using System.Linq;
public class Demo {
public static void Main() {
try {
// Empty sequence - throws InvalidOperationException
int[] empty = { };
int result1 = empty.Single();
}
catch (InvalidOperationException ex) {
Console.WriteLine("Empty sequence error: " + ex.Message);
}
try {
// Multiple elements - throws InvalidOperationException
int[] multiple = { 1, 2, 3 };
int result2 = multiple.Single();
}
catch (InvalidOperationException ex) {
Console.WriteLine("Multiple elements error: Sequence contains more than one element");
}
}
}
The output of the above code is −
Empty sequence error: Sequence contains no elements Multiple elements error: Sequence contains more than one element
Single() vs SingleOrDefault() vs First()
| Method | Behavior | Exception Conditions |
|---|---|---|
Single() |
Returns the only element | Empty sequence or more than one element |
SingleOrDefault() |
Returns the only element or default value | More than one element only |
First() |
Returns the first element | Empty sequence only |
Common Use Cases
Retrieving a unique record from a database query
Getting configuration settings that should have exactly one value
Finding a specific item in a collection when you expect exactly one match
Validating that a filter condition returns exactly one result
Conclusion
The Single() method is ideal when you need exactly one element from a sequence and want to ensure data integrity. It provides built-in validation by throwing exceptions for empty sequences or multiple elements, making your code more robust and predictable.
