This question already has an answer here:
Multiple Order By with LINQ [duplicate]
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
为了说明起见...假设我有一个由数据库中的表生成的表。

该表包含3条信息,FlightDateAircraftPre / Post

因此,其背后的逻辑是每天应该有飞行前和飞行后。

现在,为清楚起见,我们可以说到目前为止的表格如下:

  |Date|    |    |Aircraft|    |    |Pre / Post|

 04/08/2016 |     aircraft1    |      Pre-Flight
 04/08/2016 |     aircraft3    |      Pre-Flight
 04/08/2016 |     aircraft2    |      Pre-Flight
 04/08/2016 |     aircraft3    |      Post-Flight
 04/08/2016 |     aircraft1    |      Post-Flight
 04/08/2016 |     aircraft2    |      Post-Flight


如您所见,该表没有排序(也许日期除外,但我只是编造了)。

现在我想发生的是页面加载显示此表时,该表由Aircraft排序,并且该Pre / Post基于Date ...

所以本质上我在寻找什么:

  |Date|     |    |Aircraft|    |    |Pre / Post|

 04/08/2016  |     aircraft1    |     Pre-Flight
 04/08/2016  |     aircraft1    |     Post-Flight
 04/08/2016  |     aircraft2    |     Pre-Flight
 04/08/2016  |     aircraft2    |     Post-Flight
 04/08/2016  |     aircraft3    |     Pre-Flight
 04/08/2016  |     aircraft3    |     Post-Flight
 04/09/2016  |     aircraft1    |     Pre-Flight
 04/09/2016  |     aircraft1    |     Post-Flight
 etc         |     etc          |     etc


有没有一种方法可以使用.OrderBy方法实现此结果?

最佳答案

您可以将多个OrderBy()调用链接在一起,方法是分别将第一个跟在ThenBy()ThenByDescending()之后:

// This would order by FlightDate, Aircraft then PrePost
var aircraftFlights = context.AircraftFlights.OrderBy(a => a.FlightDate)
                                             .ThenBy(a => a.Aircraft)
                                             .ThenBy(a => a.PrePost);


由于您希望飞行前值始终在飞行前值之前,因此您可以考虑为该列明确使用OrderByDescending()(因为Pre-在后字母之后):

// Consider using ThenByDescending to get your Pre/Post ordering correct
.ThenBy(a => a.PrePost);


您可以根据自己的需要进行定制。基本上,一旦您调用了第一个OrderBy()调用,您的收藏集就会成为一个OrderedEnumerable,它公开了ThenBy()ThenByDescending()调用并将处理将它们链接在一起的情况。

关于c# - 通过3个不同的属性订购,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36552474/

10-13 06:46