CSharp - LINQ First

Introduction

The First operator returns the first element of a sequence or the first element of a sequence matching a predicate.

Prototypes

There are two prototypes we cover.

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

This prototype returns the first element of the sequence.

The second prototype of the First operator allows a predicate to be passed.

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

This version of the First operator returns the first element it finds for which the predicate returns true.

If no elements cause the predicate to return true, the First operator throws an InvalidOperationException.

Exceptions

  • ArgumentNullException is thrown if any arguments are null.
  • InvalidOperationException is thrown if the source sequence is empty or if the predicate never returns true.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program// w w  w  .j a  va  2  s . c om
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        string name = codeNames.First();
        Console.WriteLine(name);
    }
}

Result

Related Topics