Home > Software design >  Can I use LINQ First() and return null if no item is found?
Can I use LINQ First() and return null if no item is found?

Time:03-31

I am traversing a list as follows:

var user = Userlist.FirstOrDefault(t => t.userId == currentUserId);
if (user != null)
{ 
    //do whatever 
}

If no element is found, it returns null and I can check for it.

But if I use .First(), it is a bit quicker. But if no element is found it gives a sequence error, Sequence contains no matching element

var user = Userlist.First(t => t.userId == currentUserId);

So, can I use the First() in LINQ, and if no element is found, do a check first before proceeding, because I found that First() is quicker?

CodePudding user response:

No, IEnumerable<T>.First() intentionally throws an exception if no matching item is found in the enumerable. This is by design, and it is why the FirstOrDefault() extension exists.

First() and FirstOrDefault() should have very similar (if not the same) performance. They will both execute in O(n) time.

When you consider that First() will generate an exception if a matching element cannot be found, the performance hit from that exception will almost certainly be significantly worse than doing a null check. Null checks are extremely fast.

  • Related