FirstOrDefault is a LINQ functionality to return first element of the collection or default value if requested item does not exist. In case of collection of reference type objects the default is null, whilst in case of value types the default depends on the particular type (e.g. for int it is 0).
FirstOrDefault 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
Let’s create example collection of integers:
And execute FirstOrDefault function to get first element:
Print to screen:
Result:
Now let’s clear the list to see what happens if we run FirstOrDefault on empty collection.
Execute FirstOrDefault:
Print to screen:
Result:
The result is 0 because there was no element on the list, so query returned default value of int type.
2. Collection of integers – with condition
Let’s use the same collection as in above example:
And use FirstOrDefault with a condition to get first item greater than 5:
Print to screen:
Result:
Now let’s change a condition and try to get first element greater than 50:
Print to screen:
Result:
The result is 0 because numbers collection doesn’t contain any item greater than 50.
3. Collection of objects – no condition
Let’s create example Car class.
And collection of cars.
Now use FirstOrDefault to get first car:
Print to screen:
Result:
Let’s clear the list and see what happens if we run FirstOrDefault on empty cars collection.
Get first element or default value:
Print to screen:
When we try to run it our application crashes because of NullReferenceException. The reason is we try to access Color and Seats properties not having the instance of Car object. As the collection is empty the variable firstOrDefaultCar equals null.
When using FirstOrDefault it is recommended to validate whether the result is actual value or default one.
Now the application works without any crashes and the result is:
4. Collection of objects – with condition
Let’s create yet another collection of cars. It’s very similar to the one from previous example but now we’ve got two blue cars.
We want to get first blue car, so need to call FirstOrDefault with appropriate condition:
Print to screen:
Result:
Now let’s change a condition and try to get first yellow car from the list:
Print to screen:
Application crashes again because of NullReferenceException. It is because there is no yellow car on the list.
We can validate it with appropriate if statement:
Result:
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW