开发者

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

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.
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜