Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c# - 何时使用.First以及何时将.FirstOrDefault与LINQ结合使用?(When to use .First and when to use .FirstOrDefault with 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以及何时将.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); 
  ask by Metro Smurf translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would use First() when I know or expect the sequence to have at least one element.

(当我知道或期望序列具有至少一个元素时,我将使用First() 。)

In other words, when it is an exceptional occurrence that the sequence is empty.

(换句话说,当序列异常为空时,则为空。)

Use FirstOrDefault() when you know that you will need to check whether there was an element or not.

(当您知道需要检查是否有元素时,请使用FirstOrDefault() 。)

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).

((这是不好的做法,可能会损害性能)。)

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()Take(1)之间的区别在于, First()返回元素本身,而Take(1)返回一系列元素,其中仅包含一个元素。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...