Linq, OrderByDescending, First, and the nefarious DefaultIfEmpty

爱⌒轻易说出口 提交于 2019-12-01 17:04:03

问题


Hopefully this is a simple matter of me not understanding something basic. Below are two Linq statements from an 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();

entities.Periods is a set containing two Period objects, each with a unique UID.

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

In my environment, however, they are not.

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

p2, however, is not correct (i.e. it is equal to the other Period in the set).

Any ideas?


回答1:


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

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


来源:https://stackoverflow.com/questions/7615237/linq-orderbydescending-first-and-the-nefarious-defaultifempty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!