Introduction
In this article, we will learn about the difference between First FirstOrDefault and Single SingleOrDefault. We can better understand this step by step.
First()
Returns the first element of a collection, or the first element that satisfies a condition. Let's make it clear with an example
Example 1
class Program {
static void Main() {
IList < int > intList = new List < int > () {
7,
10,
21,
30,
45,
50,
87
};
Console.WriteLine(" intList: {0} ", intList.First());
}
}
OUTPUT

Example 2
class Program {
static void Main() {
IList < string > strList = new List < string > () {
null,
"Two",
"Three",
"Four",
"Five"
};
Console.WriteLine("strList: {0}", strList.First());
}
}
OUTPUT
Output is blank because First() is not showing null value

Example 3
class Program {
static void Main() {
IList < string > emptyList = new List < string > ();
Console.WriteLine(emptyList.First());
}
}
OUTPUT
System.InvalidOperationException because of First() function gives an error if Collection is empty.
Example 4
class Program {
static void Main() {
IList < string > strList = new List < string > () {
"Two",
"Three",
"Four",
"Five"
};
Console.WriteLine("First() : {0}", strList.First(x => x.Contains('T')));
}
}
OUTPUT

FirstOrDefault()
Returns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range.
Example 1
class Program {
static void Main() {
IList < int > intList = new List < int > () {
7,
10,
21,
30,
45,
50,
87
};
Console.WriteLine(" intList: {0} ", intList.FirstOrDefault());
}
}
OUTPUT

Example 2
class Program {
static void Main() {
IList < string > strList = new List < string > () {
null,
"Two",
"Three",
"Four",
"Five"
};
Console.WriteLine("strList: {0}", strList.FirstOrDefault());
}
}
OUTPUT
Output is blank because FirstOrDefault() is not showing null value

Example 3
class Program {
static void Main() {
IList < string > emptyList = new List < string > ();
Console.WriteLine(emptyList.First());
}
}
OUTPUT

Example 4
class Program {
static void Main() {
IList < string > strList = new List < string > () {
"Two",
"Three",
"Four",
"Five"
};
Console.WriteLine("First() : {0}", strList.FirstOrDefault(x => x.Contains('T')));
}
}








Join the conversation! Your thoughts help the community grow.