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)
var listItem = list.FirstOrDefault(x => x.Foo == Foo);
if (listItem != null)
{
//Do stuff
}
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
}
you can use the "is" operator :)
List<T> list;
if (list.Find(x => x.Foo == Foo) is T yourObject)
{
//do stuff with yourObject.
}
精彩评论