为什么要在LINQ使用第一,而不是FirstOrDefault? [英] Why use First instead of FirstOrDefault in LINQ?

查看:116
本文介绍了为什么要在LINQ使用第一,而不是FirstOrDefault?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/1024559/when-to-use-first-and-when-to-use-firstordefault-with-linq">When使用。首先,何时使用.FirstOrDefault使用LINQ?

使用首先运营商在LINQ,当你可以使用 FirstOrDefault 操盘手的要点是什么?

 变种Q = results.First(); //错误,如果空
 

解决方案

要直接回复您的具体问题(为什么要用首先如果你总是可以使用 FirstOrDefault ),有些情况下你不能使用 FirstOrDefault ,因为它失去的信息! 默认值可能是在源列表中一个有效的元素类型。你没有办法枚举中的第一个元素来区分被空/默认与那里是列表中没有的元素,除非你使用首先或者先检查是否有任何元素,这需要双重枚举。

这是尤其如此,值类型可枚举,如 INT [] 默认(INT) 0 ,这也是最有可能数组的一个有效的值。

在一般情况下,这两种方法重新present不同逻辑流。 首先将被使用,如果没有任何元素是特殊的(错误),然后想出来的带外处理您的应用程序。在这种情况下,你预期至少有一个元素。 FirstOrDefault 在一个空集,这意味着你需要做额外的处理与返回的值返回null。这是类似的逻辑对 INT 解析 VS 的TryParse 方法> / /等。事实上,在某些方面的问题导致自己为什么永远使用异常的更普遍的问题。

由于首先抛出一个异常,它适合于所有的例外提供code-重用机会。例如,你可以这样做:

 尝试
{
    X = arr1.First();
    Y = arr2.First();
    Z = arr3.First();
}
抓住
{
    抛出新的ArgumentException();
}
 

Possible Duplicate:
When to use .First and when to use .FirstOrDefault with LINQ?

What is the point of using the First operator in LINQ, when you could use the FirstOrDefault operator instead?

var q = results.First(); // Error if empty

解决方案

To respond directly to your specific question (why use First if you can always use FirstOrDefault), there are instances where you cannot use FirstOrDefault, because it loses information! The "default value" is likely a valid element type in the source list. You have no way to distinguish between the first element in the enumeration being null/default vs. there being no elements in the list unless you use First or first check if there are Any elements, which requires double-enumeration.

This is especially true for value-typed enumerables, such as int[]. default(int) is 0, which is also most likely a valid value of the array.

In general, the two methods represent different logical flows. First would be used if not having any elements is "exceptional" (an error), which then want to handle out-of-band in your application. In this scenario, you "expect" to have at least one element. FirstOrDefault returns null on an empty set, which means you need to do additional processing with the returned value. This is similar logic to the Parse vs TryParse methods on int/double/etc. In fact, your question in some ways leads itself to the more general question of why to ever use exceptions.

Since First throws an exception, it lends itself to all of the code-reuse opportunities that exceptions provide. For example, you could do:

try
{
    x = arr1.First();
    y = arr2.First();
    z = arr3.First();
}
catch
{
    throw new ArgumentException();
}

这篇关于为什么要在LINQ使用第一,而不是FirstOrDefault?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆