C# Enumerable FirstOrDefault(IEnumerable)

Description

Returns the first element of a sequence, or a default value if the sequence contains no elements.

Syntax


public static TSource FirstOrDefault<TSource>(
  this IEnumerable<TSource> source
)

Parameters

  • TSource - The type of the elements of source.
  • source - The IEnumerable to return the first element of.

Example

The following code example demonstrates how to use FirstOrDefault on an empty array.


/* www  .j a  v a 2  s  .  co m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
      int[] numbers = { };
      int first = numbers.FirstOrDefault();
      Console.WriteLine(first);

      List<int> months = new List<int> { };

      int firstMonth1 = months.FirstOrDefault();
      if (firstMonth1 == 0)
      {
          firstMonth1 = 1;
      }
      Console.WriteLine(firstMonth1);

      int firstMonth2 = months.DefaultIfEmpty(1).First();
      Console.WriteLine(firstMonth2);


  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable