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

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

    .First will throw an exception when there are no results. .FirstOrDefault won't, it will simply return either null (reference types) or the default value of the value type. (e.g like 0 for an int.) The question here is not when you want the default type, but more: Are you willing to handle an exception or handle a default value? Since exceptions should be exceptional, FirstOrDefault is preferred when you're not sure if you're going to get results out of your query. When logically the data should be there, exception handling can be considered.

    Skip() and Take() are normally used when setting up paging in results. (Like showing the first 10 results, and the next 10 on the next page, etc.)

    Hope this helps.

提交回复
热议问题