C# Enumerable SingleOrDefault(IEnumerable)
Description
Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
Syntax
public static TSource SingleOrDefault<TSource>(
this IEnumerable<TSource> source
)
Parameters
TSource
- The type of the elements of source.source
- An IEnumerableto return the single element of.
Example
The following code example demonstrates how to use SingleOrDefault to select the only element of an array.
//from w ww . j a v a 2 s . c om
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
string[] fruits1 = { "orange" };
string fruit1 = fruits1.SingleOrDefault();
Console.WriteLine(fruit1);
string[] fruits2 = { };
string fruit2 = fruits2.SingleOrDefault();
Console.WriteLine(
String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);
}
}