First is LINQ functionality to return first item of the collection or throw exception if such item does not exist.
First is overloaded method which can be used with either zero or one parameter. The first option just returns first element and the second one allows to define condition which needs to be met.
1. Collection of integers – no condition
Create a collection of random integers.
1 |
var integers = new List<int>() { 36, 10, 4, 23, 1 }; |
Execute First method to get first number from the list.
1 |
var first = integers.First(); |
Print the returned value to console.
1 |
Console.WriteLine(first); |
Result:
1 |
36 |
Now let’s clear integers collection and retry First method.
1 2 3 |
integers.Clear(); var unknown = integers.First(); |
This time when we run above code application crashes with the InvalidOperationException because there is no element on the list. It is expected behavior for First method.
We can avoid crash by running the code within try/catch statement.
1 2 3 4 5 6 7 8 9 |
try { var unknown = integers.First(); Console.WriteLine(unknown); } catch (InvalidOperationException) { Console.WriteLine("Collection is empty."); } |
Above code will result with:
1 |
Collection is empty. |
When we expect that in some cases our collection will be empty it’s better to use FirstOrDefault function and react based on received value. If the empty collection is not expected and means the faulty system behavior then it’s fine to use First and have an exception in such situation.
2. Collection of integers – with condition
Let’s reuse the list from previous example.
1 |
var integers = new List<int>() { 36, 10, 4, 23, 1 }; |
Now run the First query with the condition to get item lower than 5.
1 |
var firstBelowFive = integers.First(x => x < 5); |
Print to the screen.
1 |
Console.WriteLine(firstBelowFive); |
Result:
1 |
4 |
We received 4 as an expected result because it was first number in the collection lower than 5.
Let’s slightly modify the condition, so that no item match the criteria.
1 |
var firstBelowOne = integers.First(x => x < 1); |
Print to the console.
1 |
Console.WriteLine(firstBelowOne); |
When we run this code application crashes again because of InvalidOperationException. The reason is lack of elements lower than 1. As the First method couldn’t return any element, it threw the exception.