CSharp - LINQ FirstOrDefault


The FirstOrDefault operator returns default value when the first element cannot be found.


There are two prototypes we cover. The First FirstOrDefault Prototype.

public static T FirstOrDefault<T>(
   this IEnumerable<T> source);

This version of FirstOrDefault prototype returns the first element found in the input sequence.

If the sequence is empty, default(T) is returned.

For reference and nullable types, the default value is null.

The second prototype of the FirstOrDefault operator allows you to pass a predicate to determine which element should be returned.

public static T FirstOrDefault<T>(
    this IEnumerable<T> source,
    Func<T, bool> predicate);


ArgumentNullException is thrown if any arguments are null.

The following code shows an example of the first FirstOrDefault prototype where no element is found.

We have to get an empty sequence by calling Take(0) for this purpose.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from   ww  w .  java2 s.  c o  m*/
    static void Main(string[] args)
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        string name = codeNames.Take(0).FirstOrDefault();
        Console.WriteLine(name == null ? "NULL" : name);


Related Topics