问题:
I've searched around and haven't really found a clear answer as to when you'd want to use .First
and when you'd want to use .FirstOrDefault
with LINQ. 我到处搜索,还没有真正找到关于何时使用.First
以及何时将.FirstOrDefault
与LINQ结合使用的明确答案。
When would you want to use
.First
? 您什么时候要使用.First
? Only when you'd want to catch the exception if no results where returned? 仅当您希望在没有返回结果的情况下捕获异常时?var result = List.Where(x => x == "foo").First();
And when would you want to use
.FirstOrDefault
? 以及何时要使用.FirstOrDefault
? When you'd always want the default type if no result? 如果没有结果,何时总是需要默认类型?var result = List.Where(x => x == "foo").FirstOrDefault();
And for that matter, what about Take? 那么,Take呢?
var result = List.Where(x => x == "foo").Take(1);
解决方案:
参考一: https://stackoom.com/question/4IX9/何时使用-First以及何时将-FirstOrDefault与LINQ结合使用参考二: https://oldbug.net/q/4IX9/When-to-use-First-and-when-to-use-FirstOrDefault-with-LINQ
来源:oschina
链接:https://my.oschina.net/u/4432649/blog/4327055