Find() and First() throws exceptions, how to return null instead?
Solution 1:
var listItem = list.FirstOrDefault(x => x.Foo == Foo);
if (listItem != null)
{
//Do stuff
}
Solution 2:
Bala R's answer is correct, I just wanted to add a piece of information:
Note that if List<T>
contains objects that by-design cannot be null, the FirstOrDefault
will return something else than null
. The compiler is likely to give a warning/error of this at the if statement. In that case you should approach your situation like this:
List<MyObjectThatCannotBeNull> list;
var listItem = list.FirstOrDefault(x => x.Foo == Foo);
if (!listItem.Equals(default(MyObjectThatCannotBeNull)))
{
//Do stuff
}