我到处搜索,并没有真正找到一个明确的答案,什么时候你想使用. first,什么时候你想使用. firstordefault与LINQ。

什么时候你想用。first ?只有当你想捕捉异常,如果没有结果返回哪里? var result =列表。Where(x => x == "foo").First(); 什么时候使用。firstordefault ?当你总是想默认类型,如果没有结果? var result =列表。Where(x => x == "foo").FirstOrDefault(); 说到这,那塔克呢? var result =列表。Where(x => x == "foo").Take(1);


当前回答

另一个需要注意的区别是,如果您在生产环境中调试应用程序,您可能无法访问行号,因此识别方法中哪个特定的. first()语句抛出异常可能很困难。

异常消息也不包括您可能使用过的任何Lambda表达式,这会使任何问题更难调试。

这就是为什么我总是使用FirstOrDefault(),即使我知道空条目将构成异常情况。

var customer = context.Customers.FirstOrDefault(i => i.Id == customerId);
if (customer == null)
{
   throw new Exception(string.Format("Can't find customer {0}.", customerId));
}

其他回答

第一:

返回序列的第一个元素 抛出异常:结果中没有元素 使用when:当期望有多个元素,而您只想要第一个元素时

FirstOrDefault:

返回序列的第一个元素,如果没有找到元素,则返回默认值 抛出异常:仅当源为空时 使用when:当期望有多个元素,而您只想要第一个元素时。同样,结果为空也是可以的

来自:http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/

这种类型的函数属于元素操作符。下面定义了一些有用的元素操作符。

第一/ FirstOrDefault 去年/ LastOrDefault 单/ SingleOrDefault

当需要根据特定条件从序列中选择单个元素时,我们使用元素操作符。这里有一个例子。

  List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };

First()操作符返回序列满足条件后的第一个元素。如果没有找到元素,则抛出异常。

Int result = items。Where(item => item == 2).First();

FirstOrDefault()操作符返回满足条件后序列的第一个元素。如果没有找到元素,则返回该类型的默认值。

Int result1 = items。Where(item => item == 2).FirstOrDefault();

.First will throw an exception when there are no results. .FirstOrDefault won't, it will simply return either null (reference types) or the default value of the value type. (e.g like 0 for an int.) The question here is not when you want the default type, but more: Are you willing to handle an exception or handle a default value? Since exceptions should be exceptional, FirstOrDefault is preferred when you're not sure if you're going to get results out of your query. When logically the data should be there, exception handling can be considered.

Skip()和Take()通常在设置结果分页时使用。(比如显示前10个结果,接下来的10个在下一页,等等)

如果没有要返回的行,. first()将抛出异常,而. firstordefault()将返回默认值(所有引用类型为NULL)。

因此,如果你准备好并愿意处理一个可能的异常,. first()是很好的。如果您更喜欢检查!= null的返回值,那么. firstordefault()是更好的选择。

但我想这也有点个人偏好。使用哪个对你更有意义,更适合你的编码风格。

好吧,让我说说我的意见。 First / Firstordefault用于使用第二个构造函数。我不会解释它是什么,但它是指你可能总是使用一个,因为你不想引起异常。

person = tmp.FirstOrDefault(new Func<Person, bool>((p) =>
{
    return string.IsNullOrEmpty(p.Relationship);
}));