C# Enumerable Single(IEnumerable, Func)
Description
Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
Syntax
public static TSource Single<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
Parameters
TSource
- The type of the elements of source.source
- An IEnumerableto return a single element from. predicate
- A function to test an element for a condition.
Example
The following code example demonstrates how to use Single to select the only element of an array that satisfies a condition.
// w ww . j a v a2 s.co m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
string[] fruits = { "apple", "banana", "mango"};
string fruit1 = fruits.Single(fruit => fruit.Length > 3);
Console.WriteLine(fruit1);
}
}