Find()和 First()抛出异常,如何返回 null?

在搜索列表时,是否有返回 null 而不是抛出异常的 linq lambda 搜索方法?

我目前的解决方案是这样的: (避免抛出异常)

if (list.Exists(x => x.Foo == Foo))
{
var listItem = list.Find(x => x.Foo == Foo);
}

我只是觉得不该重复这句话。

比如..。

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

我感觉好多了,还是只有我这么觉得?

你有更好的办法吗?(解决方案不必返回 null,只需更好的解决方案即可)

87448 次浏览
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.
}