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

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

    Ok let me give my two cents. First / Firstordefault are for when you use the second constructor. I won't explain what it is, but it's when you would potentially always use one because you don't want to cause an exception.

    person = tmp.FirstOrDefault(new Func<Person, bool>((p) =>
    {
        return string.IsNullOrEmpty(p.Relationship);
    }));
    
    0 讨论(0)
  • 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));
    }
    
    0 讨论(0)
  • 2020-11-22 09:38

    I would use First() when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.

    Use FirstOrDefault() when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).

    Finally, the difference between First() and Take(1) is that First() returns the element itself, while Take(1) returns a sequence of elements that contains exactly one element.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:40

    linq many ways to implement single simple query on collections, just we write joins in sql, a filter can be applied first or last depending on the need and necessity.

    Here is an example where we can find an element with a id in a collection. To add more on this, methods First, FirstOrDefault, would ideally return same when a collection has at least one record. If, however, a collection is okay to be empty. then First will return an exception but FirstOrDefault will return null or default. For instance, int will return 0. Thus usage of such is although said to be personal preference, but its better to use FirstOrDefault to avoid exception handling.

    0 讨论(0)
  • 2020-11-22 09:42
    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.

    0 讨论(0)
提交回复
热议问题