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

Ben Galler picture Ben Galler · Apr 10, 2011 · Viewed 72k times · Source

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)

Answer

Bala R picture Bala R · Apr 10, 2011
var listItem = list.FirstOrDefault(x => x.Foo == Foo);
if (listItem != null)
{
    //Do stuff
}