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

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

    Another difference to note is that if you're debugging an application in a Production environment you might not have access to line numbers, so identifying which particular .First() statement in a method threw the exception may be difficult.

    The exception message will also not include any Lambda expressions you might have used which would make any problem even are harder to debug.

    That's why I always use FirstOrDefault() even though I know a null entry would constitute an exceptional situation.

    var customer = context.Customers.FirstOrDefault(i => i.Id == customerId);
    if (customer == null)
    {
       throw new Exception(string.Format("Can't find customer {0}.", customerId));
    }
    

提交回复
热议问题