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

后端 未结 14 1442
无人共我
无人共我 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:39

    I found a website that apperars to explain the need for FirstOrDefault
    http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/
    If there are no results to a query, and you want to to call First() or Single() to get a single row... You will get an “Sequence contains no elements” exception.

    Disclaimer: I have never used LINQ, so my apologies if this is way off the mark.

提交回复
热议问题