使用linq反转对象列表中的对象列表

时间:2012-09-21 07:26:44

标签: vb.net asp.net-mvc-3 linq linq-to-objects

我有一个班级类型酒店列表,其中包含其他教室的列表。现在,当我执行降序排序时,我按降序排序酒店,但我还必须使用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个索引房间的费用最低。同样以降序排序我还想对房间列表进行排序。

提前致谢。

3 个答案:

答案 0 :(得分: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 

可能会有所帮助。

答案 1 :(得分:0)

根据您想要的结果,您可能需要.ThenBy

首先,这是我正在使用的LINQ表达式:

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

使用LINQpad我得到了这个:

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)

(但这是未经测试的 - 它基于已经为另一个SO答案编码的略有不同的数据集的AsQueryable输出。)

答案 2 :(得分: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的整个酒店实例。