何时使用 .First 以及何时使用 .FirstOrDefault 与 LINQ? [英] When to use .First and when to use .FirstOrDefault with LINQ?

查看:40
本文介绍了何时使用 .First 以及何时使用 .FirstOrDefault 与 LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处搜索,并没有真正找到明确的答案,说明您何时需要使用 .First 以及何时需要使用 .FirstOrDefault 使用 LINQ.

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?仅当您想在没有返回结果的情况下捕获异常时?

  • When would you want to use .First? Only when you'd want to catch the exception if no results where returned?

var result = List.Where(x => x == "foo").First();

  • 什么时候使用.FirstOrDefault?如果没有结果,你总是想要默认类型?

  • And when would you want to use .FirstOrDefault? When you'd always want the default type if no result?

    var result = List.Where(x => x == "foo").FirstOrDefault();
    

  • 那么,Take 呢?

  • And for that matter, what about Take?

    var result = List.Where(x => x == "foo").Take(1);
    

  • 推荐答案

    当我知道或期望序列至少包含一个元素时,我会使用 First().换句话说,当序列为空的异常情况时.

    I would use First() when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.

    当您知道需要检查是否存在元素时,请使用 FirstOrDefault().换句话说,当序列为空时是合法的.您不应依赖异常处理进行检查.(这是不好的做法,可能会影响性能).

    Use FirstOrDefault() when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).

    最后,First()Take(1) 的区别在于 First() 返回元素本身,而 Take(1) 返回包含一个元素的元素序列.

    Finally, the difference between First() and Take(1) is that First() returns the element itself, while Take(1) returns a sequence of elements that contains exactly one element.

    这篇关于何时使用 .First 以及何时使用 .FirstOrDefault 与 LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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