如何在 Linq 中使用列表对组结果进行排序?

How do I order a group result with a list, in Linq?

此 linq 将所有房间作为按 rateCode 分组的列表提供给我。

var results = (from r in dcCrs.CRS_RateTypePerReservation
                   where r.Reservation_id_fk == reservation.Reservation_id_pk 
                      && r.RoomTypeCenter_id_fk != null 
                      && r.Price != 0
               group r.RoomTypesPerCenter.RoomTypes.Code by r.CRS_RateTypes.Name into g
               select new { rateCode = g.Key, roomName = g.ToList() });

但现在我必须按数据库中的整数对结果进行排序,命名为 Order:

var results = (from r in dcCrs.CRS_RateTypePerReservation
                   where r.Reservation_id_fk == reservation.Reservation_id_pk 
                      && r.RoomTypeCenter_id_fk != null 
                      && r.Price != 0
                   orderby r.Order ascending
                   group r.RoomTypesPerCenter.RoomTypes.Code by r.CRS_RateTypes.Name into g
                   select new { rateCode = g.Key, roomName = g.ToList() });

这只会对房间的名称进行排序,而不是对两者进行排序。

数据:

Order   Rates      RoomType 
5       PER        DBL  
30      PER        IND
15      BAR        IND
10      BAR        DBL  
20      BAR        URB  

它应该给出这个结果,因为第一个是 5 和 30 (PER),然后是 10、15 和 20 (BAR):

   {rateCode = PER, roomName = {DBL, IND} }

   {rateCode = BAR, roomName = {DBL, IND, URB} }

但它 returns 我这个:

   {rateCode = BAR, roomName = {DBL, IND, URB} }

   {rateCode = PER, roomName = {DBL, IND} }

感谢任何建议。

数据库键的顺序GROUP BY查询结果未定义。

分组后需要申请排序,像这样

var results = 
   (from r in dcCrs.CRS_RateTypePerReservation
    where r.Reservation_id_fk == reservation.Reservation_id_pk 
        && r.RoomTypeCenter_id_fk != null 
        && r.Price != 0
    group r by r.CRS_RateTypes.Name into g
    orderby g.Min(r => r.Order)
    select new
    {    
        rateCode = g.Key,
        roomName = (from r in g orderby r.Order select r.RoomTypesPerCenter.RoomTypes.Code).ToList()
    });