When to use .First and when to use .FirstOrDefault

2018-12-31 16:02发布

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 with LINQ.

  • When would you want to use .First? Only when you'd want to catch the exception if no results where returned?

    var result = List.Where(x => x == "foo").First();
    
  • And when would you want to use .FirstOrDefault? When you'd always want the default type if no result?

    var result = List.Where(x => x == "foo").FirstOrDefault();
    
  • And for that matter, what about Take?

    var result = List.Where(x => x == "foo").Take(1);
    

标签: c# .net linq
14条回答
与君花间醉酒
2楼-- · 2018-12-31 16:32

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

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 16:33

First:

  • Returns the first element of a sequence
  • Throws exception: There are no elements in the result
  • Use when: When more than 1 element is expected and you want only the first

FirstOrDefault:

  • Returns the first element of a sequence, or a default value if no element is found
  • Throws exception: Only if the source is null
  • Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/

查看更多
其实,你不懂
4楼-- · 2018-12-31 16:34

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));
}
查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 16:38
someList.First(); // exception if collection is empty.
someList.FirstOrDefault(); // first item or default(Type)

Which one to use? It should be decided by the business logic, and not the fear of exception/programm failure.

For instance, If business logic says that we can not have zero transactions on any working day (Just assume). Then you should not try to handle this scenario with some smart programming. I will always use First() over such collection, and let the program fail if something else screwed up the business logic.

Code:

var transactionsOnWorkingDay = GetTransactionOnLatestWorkingDay();
var justNeedOneToProcess = transactionsOnWorkingDay.First(): //Not FirstOrDefault()

I would like to see others comments over this.

查看更多
笑指拈花
6楼-- · 2018-12-31 16:39

First of all, Take is a completely different method. It returns an IEnumerable<T> and not a single T, so that's out.

Between First and FirstOrDefault, you should use First when you're sure that an element exists and if it doesn't, then there's an error.

By the way, if your sequence contains default(T) elements (e.g. null) and you need to distinguish between being empty and the first element being null, you can't use FirstOrDefault.

查看更多
残风、尘缘若梦
7楼-- · 2018-12-31 16:40

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

查看更多
登录 后发表回答