When to use .First and when to use .FirstOrDefault with LINQ?

后端 未结 14 1441
无人共我
无人共我 2020-11-22 09:09

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 wit

14条回答
  •  悲哀的现实
    2020-11-22 09:38

    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.

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

    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.

提交回复
热议问题