LastOrDefault
In this chapter you will learn:
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:
Home » C# Tutorial » Linq Operators