本文介绍了Linq,OrderByDescending,First和恶意的DefaultIfEmpty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这是我不了解基本知识的简单问题.以下是我正在处理的应用程序中的两个Linq语句.

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是一个包含两个Period对象的集合,每个对象都有一个unique UID.

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

据我了解,p1和p2应该相同.

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

但是,在我的环境中,事实并非如此.

In my environment, however, they are not.

p1是正确的(即,它等于集合中UID最大的Period对象).

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

p2不正确(即等于集合中的另一个期间).

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

有什么想法吗?

推荐答案

DefaultIfEmpty()不能保证维持由OrderByDescending()建立的顺序,(另请参见)顺序应始终为最后,这就是第一种情况有效的原因-但您不应该用我认为的任何一种-这正是FirstOrDefault()的用途:

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();

这篇关于Linq,OrderByDescending,First和恶意的DefaultIfEmpty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:18