0

我有一个类类型酒店的列表,其中包含其他类房间的列表。现在,当我执行降序排序时,我按降序对酒店进行排序,但我还必须使用 linq 在内部按价格对房间列表进行排序。下面是类结构的草图

class Hotel
       - property hotelname (string)
       - property rooms  (list of rooms)

class rooms
      - property roomdesc (string)
      - property roomcharge (decimal)

我现在以下面的方式应用了降序和升序代码。

lstHotels.OrderByDescending(Function(hotel) hotel.Rooms(0).roomcharge).ToList()

这会根据房间费用对酒店进行降序排序。第 0 个索引房间总是成本最低。同样使用降序排序,我还想对房间列表进行排序。

提前致谢。

4

3 回答 3

0

Depending what result you want, you could just need .ThenBy:

Firstly, here is the LINQ expression I'm using:

From hotel In lstHotels
    From room In hotel.Rooms
    Order By hotel.Room(0).roomcharge Descending,
             room.roomcharge Descending    

Using LINQpad I get this:

lstHotels.SelectMany(Function(hotel) hotel.Rooms, _
            Function(hotel,room) New With{.hotel=hotel, .room=room}) _
     .OrderByDescending(Function(hr) hr.hotel.Rooms(0).roomcharge) _
     .ThenByDescending(Function(hr) hr.room.roomcharge)

(but this is untested -- it is based upon the AsQueryable output from a slightly different dataset already coded for another SO answer).

于 2012-09-23T17:49:13.827 回答
0

假设您有这些课程:

public class Hotel
{
    public string Name { get; set; }
    public List<Room> Rooms { get; set; } // List<Room> to keep it simple, 
                                          // you could/should expose it 
                                          // in a better way
}

public class Room
{
    public string Description { get; set; }
    public decimal Charge { get; set; }
}

我认为正确的方法不是对Rooms成员进行排序,而是进行 Linq 查询,通过匿名类型在新数据结构中投射所需的排序:

var report = from o in offers
             orderby o.Name descending
             select new 
             { 
                o.Name, 
                Rooms = from r in o.Rooms
                        orderby r.Charge
                        select r 
             };

这样,您就有了匿名类型的枚举,其中第一个成员是酒店的名称,第二个成员是按您想要的方式排序的房间的枚举。您可能希望根据自己的喜好在投影中公开整个酒店实例,替换o.Name为。Hotel = o

于 2012-09-24T14:35:13.443 回答
0

如果我正确理解了这个问题,你想颠倒酒店房间的顺序,如果是这样,那么你可以试试这个。

Dim hotelList as List(Of Hotel) =  lstHotels.OrderByDescending(Function(hotel) hotel.Rooms(0).roomcharge).ToList()

hotelList.ForEach(AddressOf OrderRooms)


Sub OrderRooms(ByVal hotel As Hotel)
       hotel.Rooms.Reverse()
End Sub 

可能会有所帮助。

于 2012-09-21T07:38:35.203 回答