FirstOrDefault
In this chapter you will learn:
- C# Linq FirstOrDefault operator
- FirstOrDefault with filter delegate
- Get the first or the default
- FirstOrDefault vs First
- FirstOrDefault and string operation
- FirstOrDefault with a Not Found Element
Get to know FirstOrDefault
FirstOrDefault
returns null when an Element Is Found.
using System;/* j ava 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.FirstOrDefault();
Console.WriteLine(name == null ? "NULL" : name);
}
}
FirstOrDefault with filter delegate
using System;/*from j a v a2 s . c o m*/
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = { 1, 3, 5, 7, 9 };
var query = numbers.FirstOrDefault(n => n % 2 == 0);
}
}
Get the first or the default
using System;//from java 2s . c o m
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
int[] numbers = { };
int firstNumOrDefault = numbers.FirstOrDefault();
Console.WriteLine(firstNumOrDefault);
}
}
FirstOrDefault vs First
The following demonstrates First
versus FirstOrDefault
:
using System;/* j ava2s.c o m*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
int firstBigError = numbers.First(n => n > 10); // Exception
int firstBigNumber = numbers.FirstOrDefault(n => n > 10); // 0
Console.WriteLine(firstBigError);
Console.WriteLine(firstBigNumber);
}
}
The output:
FirstOrDefault and string operation
using System;/*from ja v a 2s. 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.FirstOrDefault(p => p.StartsWith("B"));
Console.WriteLine(name == null ? "NULL" : name);
}
}
FirstOrDefault with a Not Found Element
using System;/*from java 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).FirstOrDefault();
Console.WriteLine(name == null ? "NULL" : name);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Linq Operators