advertise with us

C# – LINQ First Examples

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.

Execute First method to get first number from the list.

Print the returned value to console.

Result:

Now let’s clear integers collection and retry First method.

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.

Above code will result with:

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.

Now run the First query with the condition to get item lower than 5.

Print to the screen.

Result:

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.

Print to the console.

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.


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