If we have an EF entity with basic structure of
public class Entity
{
public int Id {get; set;}
public string name {get; set;}
public DateTime lastUpdated {get; set;}
}
And a collection of them with 4 entities:
entities = new List<Entity>{
new { Id = 0, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 1, 0, 0, 0,)},
new { Id = 1, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 4, 0, 0, 0,)},
new { Id = 2, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 3, 0, 0, 0,)},
new { Id = 3, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 2, 0, 0, 0,)}
};
If we use Linq to select the FirstOrDefault
by the Name property.
var selectedEntity = entities.FirstOrDefault(e => e.Name == "Thing One");
What is this going to return?
This is causing issues in a piece of code that I'm reviewing; which will be fixed by only allowing unique entities and using SingleOrDefault
, but I'm curious at to what the FirstOrDefault
is going to return by default when there is no OrderBy
clause.
CodePudding user response:
The first item matching this condition is returned, if there are multiple items matching the result is unpredictable/undefined. If you want to ensure a specifc item you need to apply an OrderBy
:
var selectedEntity = entities
.Where(e => e.Name == "Thing One")
.OrderByDescending(e => e.LastUpdated)
.FirstOrDefault();
What is returned by the database depends on the vendor. This related qustion might help: When no 'Order by' is specified, what order does a query choose for your record set?