何时使用 .First 以及何时将 .FirstOrDefault 与 LINQ 一起使用?

编程入门 行业动态 更新时间:2024-10-11 13:28:31
本文介绍了何时使用 .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 一起使用?

    本文发布于:2023-11-22 00:23:59,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1615257.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:时将   FirstOrDefault   LINQ

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!