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

C#.NetLinqLambda

C# Problem Overview


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)

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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
}

Solution 3 - C#

you can use the "is" operator :)

  List<T> list;
  if (list.Find(x => x.Foo == Foo) is T yourObject)
  {
     //do stuff with yourObject.
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen GallerView Question on Stackoverflow
Solution 1 - C#Bala RView Answer on Stackoverflow
Solution 2 - C#BazzzView Answer on Stackoverflow
Solution 3 - C#G ClovsView Answer on Stackoverflow