Last

In this chapter you will learn:

  1. How to use Last operator
  2. Last operator with string operation
  3. Last operator with filter delegate

Get to know Last operator

using System;/*java 2  s  .  c  om*/
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.Last();
        Console.WriteLine(name);
    }
}

Last operator with string operation

using System;/* j a v  a2s  .  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.Last(p => p.StartsWith("H"));
        Console.WriteLine(name);
    }
}

Last operator with filter delegate

using System;//  java2s  .  co m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        int last = numbers.Last();  // 5

        int lastEven = numbers.Last(n => n % 2 == 0); // 4

        Console.WriteLine(last);
        Console.WriteLine(lastEven);
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to use LastOrDefault operator
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