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

后端 未结 14 1670
无人共我
无人共我 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条回答
  •  猫巷女王i
    2020-11-22 09:26

    .First() will throw an exception if there's no row to be returned, while .FirstOrDefault() will return the default value (NULL for all reference types) instead.

    So if you're prepared and willing to handle a possible exception, .First() is fine. If you prefer to check the return value for != null anyway, then .FirstOrDefault() is your better choice.

    But I guess it's a bit of a personal preference, too. Use whichever makes more sense to you and fits your coding style better.

提交回复
热议问题