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)
返回一系列元素,其中仅包含一个元素。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…