0

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.

Ross Halliday
  • 785
  • 6
  • 19
  • it's just undefined. in programming there's many such cases. in my opinion useless to study the behaviour. – Lei Yang Feb 08 '22 at 13:59

1 Answers1

0

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?

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    cheers! the articles in the linked answer are very interesting. Relying on a FirstOrDefault with no ordering is certainly going to turn up in bug somewhere :-) – Ross Halliday Feb 08 '22 at 14:24
  • @RossHalliday: You're welcome. Yes, especially the first article is worth reading: https://web.archive.org/web/20160808070425/https://blogs.msdn.microsoft.com/conor_cunningham_msft/2008/08/27/no-seatbelt-expecting-order-without-order-by/ – Tim Schmelter Feb 08 '22 at 14:42