如何在 Linq 中对带有列表的组结果进行排序

本文关键字:结果 排序 列表 Linq | 更新日期: 2023-09-27 18:30:57

这个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} }

但它让我得到这个:

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

感谢您的任何建议。

如何在 Linq 中对带有列表的组结果进行排序

数据库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()
    });