Which method should you use to get the first collection's element that meets a certain condition - 'First' or 'FirstOrDefault'? What should you choose to get the last element - 'Last' or 'LastOrDefault'? At first glance, the choice may not be obvious. Hopefully, this article will answer these questions and help you decide what to choose.
Potential NullReferenceException
Let's start with a quick recap of what methods return: FirstOrDefault, LastOrDefault, SingleOrDefault, and ElementAtOrDefault. Note they all end in 'OrDefault'. They return the first element of the sequence that satisfies the passed search predicate. Also for the FirstOrDefault, LastOrDefault, and SingleOrDefault methods, there are parameter-less overloads that return the first, last, or only element of the sequence, respectively. Here is an important reminder. Let's say, there is more than one element in the sequence that meets the passed predicate. If so, the SingleOrDefault method throws an exception. The same will happen if the SingleOrDefault method is called without a predicate on a sequence containing more than one element. Example of using the FirstOrDefault method:
public static void ProcessFirstOrder(List<Order> orders) { DateTime firstDay = new DateTime(2021, 1, 1); Order firstOrder = orders.FirstOrDefault(o => o.OrderDate >= firstDay); decimal tax = GetTaxes(firstOrder.Cost); }
Let's see what happens if at least one order made in 2021 is found in the orders list. The first order variable will get a reference to an object of the Order type. If an element that meets the condition is not found, the method returns the default value for the type contained in the collection. The reference type returns null.
It often happens that developers forget to check the return value for null. This fragment occasionally triggers NullReferenceException that doesn't get you to the roots of the problem. Check out this list of similar examples. Therefore, you should always check the return value for null.
Methods that return null (in case there is no suitable element) might seem to be more reliable analogs compared to their related counterparts: First, Last, Single, ElementAt. After all, methods that do not have the 'Default' suffix in their name will throw the InvalidOperationException type exception if a suitable element was not found in the collection. No one likes when exceptions appear. So why potentially provoke an exceptional situation by using the First, Last, and other methods?
In fact, it is not right to use FirstOrDefault and LastOrDefault type methods in all possible cases. Programmers shouldn't ignore the First and Last methods anyway. As a rule of thumb, you can use the following approach:
- use the First method for cases when you are sure that there is at least one suitable element in the collection (or only one in the case of the Single method). Let's say, something went wrong - for example, the array turned out to be empty. Then you face an exceptional case that should be handled. In addition, even if the exception is not handled, the InvalidOperationException type indicates and explains the problem more clearly. By the way, the type provides a very informative message, for example, "Sequence contains no elements". Suppose one of the 'OrDefault'-like methods returned null. You might access a field, property, or method not right away but after a certain number of operations. In this case, the place in the code with the NullReferenceException type exception specified by the stack trace can lead us far from the root of the problem when we see a null reference;
- use the FirstOrDefault method for those cases when you know that the collection may not contain the element you need. So you should do another check.
Example of using the FirstOrDefault method with an additional check of the return value for null.
public static void ProcessFirstOrder(List<Order> orders) { DateTime firstDay = new DateTime(2021, 1, 1); Order firstOrder = orders.FirstOrDefault(o => o.OrderDate >= firstDay); if (firstOrder != null) { decimal tax = GetTaxes(firstOrder.Cost); .... } }
Let's recap. Don't forget to check the value returned by methods of the 'OrDefault' type for null. When you are sure that the method will not return a default value, use the methods' counterparts without 'OrDefault' in the name.
Additional links:
- StackOverflow. When to use. First and when to use.FirstOrDefault with LINQ?
- First, FirstOrDefault, Last, LastOrDefault, Single, and SingleOrDefault.
Summary
In this article, we learned when we should use methods FirstOrDefault, LastOrDefault, and SingleOrDefault and when it's preferable to use First, Last, and Single.
Author Credit
Article Type : | Guest Article |
Author : | Ilya Gainulin |
Tags : | CSharp, Knowledge |
Article Date : | 29-03-2021 |
Article Publish Date : | 27-04-2021 |
Note: All content of this article is copyright of their author. |
Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.
Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.
Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.
If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com