C# Enumerable SingleOrDefault(IEnumerable, Func)

Description

Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.

Syntax


public static TSource SingleOrDefault<TSource>(
  this IEnumerable<TSource> source,
  Func<TSource, bool> predicate
)

Parameters

  • TSource - The type of the elements of source.
  • source - An IEnumerable to return a single element from.
  • predicate - A function to test an element for a condition.

Example

The following code example demonstrates how to use SingleOrDefault to select the only element of an array that satisfies a condition.


/* w  w  w. j  a  v a 2 s  .c  o  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.SingleOrDefault(fruit => fruit.Length > 2);

    Console.WriteLine(fruit1);
    
    string fruit2 = fruits.SingleOrDefault(fruit => fruit.Length > 15);

    Console.WriteLine( String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);

  }
}




















Home »
  C# Tutorial »
    System.Linq »




Enumerable