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

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

My current solution is something like: (to throw an exception from an exception)

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

It is simply wrong to repeat the expression.

Something like...

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

... I'm better. Or is it just me?

Do you have a better approach to this? (The solution does not have to return zero, just the best solution is good)

+46
c # lambda linq
Apr 10 2018-11-11T00:
source share
2 answers
 var listItem = list.FirstOrDefault(x => x.Foo == Foo); if (listItem != null) { //Do stuff } 
+94
Apr 10 2018-11-11T00:
source share

Bala R's answer is correct, I just wanted to add some of the information:

Note that if the List<T> contains objects that cannot be empty by default, FirstOrDefault will return something else than null . The compiler will most likely give a warning / error in the if statement. In this case, you should approach your situation as follows:

 List<MyObjectThatCannotBeNull> list; var listItem = list.FirstOrDefault(x => x.Foo == Foo); if (!listItem.Equals(default(MyObjectThatCannotBeNull))) { //Do stuff } 
+28
Apr 10 2018-11-11T00:
source share



All Articles