C# Enumerable LastOrDefault(IEnumerable, Func)

Description

Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.

Syntax


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

Parameters

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

Returns

Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.

Example

The following code example demonstrates how to use LastOrDefault by passing in a predicate.


/*from   w  w w . j a  v  a2 s  .  c  om*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
      double[] numbers = { 49.6, 52.3, 51.0};

      double last50 = numbers.LastOrDefault(n => Math.Round(n) == 50.0);

      Console.WriteLine("The last number that rounds to 50 is {0}.", last50);

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable