LastOrDefault

In this chapter you will learn:

  1. How to use LastOrDefault operator

Get to know LastOrDefault operator

using System;//  java 2  s  .c o m
using System.Linq;

public class MainClass{
   public static void Main(){
      int[] numbers = { 1, 3, 5, 7, 9 };
      var query = numbers.LastOrDefault(n => n % 2 == 1);
      Console.Write(query);
   }
}

The following code shows how to use LastOrDefault method to filter string value.

using System;/* j  a  v  a  2 s . c o m*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
    public static void Main() {
        string[] presidents = {"G", "H", "a", "H", "over", "Jack"};

        string name = presidents.LastOrDefault(p => p.StartsWith("Z"));
        Console.WriteLine(name == null ? "NULL" : name);

    }
}

We can also use LastOrDefault without parameters.

using System;//  j a  v a  2s.  co m
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
    public static void Main() {
        string[] presidents = {"G", "H", "a", "H", "over", "Jack"};
        string name = presidents.Take(0).LastOrDefault();
        Console.WriteLine(name == null ? "NULL" : name);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use LongCount operator
  2. How to use LongCount with filter delegate
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip