LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

前端 未结 15 1005
我在风中等你
我在风中等你 2020-11-22 12:48

Consider the IEnumerable extension methods SingleOrDefault() and FirstOrDefault()

MSDN documents that SingleOrDefault:

相关标签:
15条回答
  • 2020-11-22 13:26

    In your last example:

    var latestCust = db.Customers
    .OrderByDescending(x=> x.CreatedOn)
    .FirstOrDefault();//Single or First, or doesn't matter?
    

    Yes it does. If you try to use SingleOrDefault() and the query results in more than record you would get and exception. The only time you can safely use SingleOrDefault() is when you are expecting only 1 and only 1 result...

    0 讨论(0)
  • 2020-11-22 13:29

    I don't understand why you're using FirstOrDefault(x=> x.ID == key) when this could retrieve results much faster if you use Find(key). If you are querying with the Primary key of the table, the rule of thumb is to always use Find(key). FirstOrDefault should be used for predicate stuff like (x=> x.Username == username) etc.

    this did not deserve a downvote as the heading of the question was not specific to linq on DB or Linq to List/IEnumerable etc.

    0 讨论(0)
  • 2020-11-22 13:30

    For LINQ -> SQL:

    SingleOrDefault

    • will generate query like "select * from users where userid = 1"
    • Select matching record, Throws exception if more than one records found
    • Use if you are fetching data based on primary/unique key column

    FirstOrDefault

    • will generate query like "select top 1 * from users where userid = 1"
    • Select first matching rows
    • Use if you are fetching data based on non primary/unique key column
    0 讨论(0)
提交回复
热议问题