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# Program to return the only element that satisfies a condition
The Single() method in C# returns the only element from a sequence that satisfies a specified condition. If no element or more than one element satisfies the condition, it throws an InvalidOperationException.
This method is part of LINQ and is commonly used when you expect exactly one element to match your criteria.
Syntax
Following is the syntax for the Single() method −
// Without condition - returns the only element public static T Single<T>(this IEnumerable<T> source) // With condition - returns the only element that matches the predicate public static T Single<T>(this IEnumerable<T> source, Func<T, bool> predicate)
Parameters
source − The sequence to search through
predicate − A function that defines the condition to test each element
Return Value
Returns the single element that satisfies the condition. Throws InvalidOperationException if zero or more than one element is found.
Using Single() with a Condition
The following example finds the only string with length greater than 4 −
using System;
using System.Linq;
public class Demo {
public static void Main() {
string[] str = { "jack", "tom", "henry", "time"};
// Finding string whose length is greater than 4
string res = str.Single(name => name.Length > 4);
Console.WriteLine("String with length > 4: " + res);
}
}
The output of the above code is −
String with length > 4: henry
Using Single() Without Condition
When used without a condition, Single() returns the only element in the sequence −
using System;
using System.Linq;
public class Demo {
public static void Main() {
int[] numbers = { 42 };
// Get the only element
int result = numbers.Single();
Console.WriteLine("The only element: " + result);
// Example with filtered sequence
int[] moreNumbers = { 1, 2, 3, 4, 5 };
int evenGreaterThanThree = moreNumbers.Where(x => x > 3 && x % 2 == 0).Single();
Console.WriteLine("Only even number > 3: " + evenGreaterThanThree);
}
}
The output of the above code is −
The only element: 42 Only even number > 3: 4
Exception Handling with Single()
The Single() method throws exceptions when conditions are not met −
using System;
using System.Linq;
public class Demo {
public static void Main() {
string[] fruits = { "apple", "banana", "cherry", "date" };
try {
// This will throw exception - multiple elements have length > 4
string result = fruits.Single(f => f.Length > 4);
Console.WriteLine(result);
}
catch (InvalidOperationException ex) {
Console.WriteLine("Exception: " + ex.Message);
}
try {
// This will throw exception - no element has length > 10
string result2 = fruits.Single(f => f.Length > 10);
Console.WriteLine(result2);
}
catch (InvalidOperationException ex) {
Console.WriteLine("Exception: " + ex.Message);
}
}
}
The output of the above code is −
Exception: Sequence contains more than one matching element Exception: Sequence contains no matching element
Single() vs SingleOrDefault()
| Single() | SingleOrDefault() |
|---|---|
| Throws exception if no element is found | Returns default value if no element is found |
| Throws exception if multiple elements are found | Throws exception if multiple elements are found |
| Use when you expect exactly one element | Use when you expect zero or one element |
Conclusion
The Single() method is ideal when you need to retrieve exactly one element from a collection that matches specific criteria. It provides built-in validation by throwing exceptions when zero or multiple matches are found, making your code more robust and predictable.
