Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find() and First() throws exceptions, how to return null instead?

Tags:

c#

.net

lambda

linq

Is there a linq lambda search method that returns null, instead of throwing an exception, when searching a list?

My current solution is something like: (to avoid exception from being thrown)

if (list.Exists(x => x.Foo == Foo)) {     var listItem = list.Find(x => x.Foo == Foo); } 

It just feels wrong to repeat the expression.

Something like ...

var listItem = list.Find(x => x.Foo == Foo); if (listItem != null) {     //Do stuff } 

... feels better to me. Or is it just me?

Do you have a better approach on this one? (The solution don't have to be returning null, just a better solution is good)

like image 608
Ben Galler Avatar asked Apr 10 '11 17:04

Ben Galler


People also ask

Is it better to return null or throw exception?

Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null. Otherwise it is a matter of preference. It certainly shouldn't be a matter of preference.

Can first or default return null?

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() returns a default value (null) if there is no result data.

What does Linq first return if not found?

Answers. First() will throw an exception if there is nothing in the result set. FirstOrDefault() will return the item or the default value. For an object this would be null.

Which of the following can be used to take the first matching element but returns null in case no matches found?

FirstOrDefault(); It returns first item if does not match query. It is better practice to check the NULL after query.


1 Answers

var listItem = list.FirstOrDefault(x => x.Foo == Foo); if (listItem != null) {     //Do stuff } 
like image 182
Bala R Avatar answered Sep 19 '22 05:09

Bala R