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

前端 未结 15 1323
我在风中等你
我在风中等你 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...

提交回复
热议问题