Linq, OrderByDescending, First and the infamous DefaultIfEmpty

Hope this is a simple question when I do not understand something basic. Below are two Linq statements from the application I'm working on.

EDMXModel.Classes.Period p1 = entities.Periods.DefaultIfEmpty(null).OrderByDescending(ap => ap.UID).First(); EDMXModel.Classes.Period p2 = entities.Periods.OrderByDescending(ap => ap.UID).DefaultIfEmpty(null).First(); 

entity.Periods is a collection containing two Period objects, each with a unique UID .

According to everything that I understand, p1 and p2 should be the same.

In my environment, however, this is not the case.

p1 is correct (i.e., it is equal to the Period object with the largest UID in the set).

p2, however, is incorrect (i.e., it is equal to another period in the set).

Any ideas?

+6
source share
1 answer

DefaultIfEmpty() in Linq to Entities does not guarantee that the order set by OrderByDescending() maintained (see also here ), the order should always be the last and that is why the first case works - but you shouldn't use it in my opinion - this is exactly what FirstOrDefault() for:

 EDMXModel.Classes.Period p1 = entities.Periods .OrderByDescending(ap => ap.UID) .FirstOrDefault(); 
+8
source

Source: https://habr.com/ru/post/898405/


All Articles