Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i use the First in Linq and return a null if no sequence is found?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading