2014-06-18 57 views
0

我有一個複雜的元素層次結構,我想根據深度爲4的子項目進行過濾。用linq過濾子項目選擇項目

這裏是類

class Hotel { 
    //other properties omitted for brevity 
    public List<Room> Rooms{get;set;} 
} 
class Room { 
    //other properties omitted for brevity 
    public List<RoomType> RoomTypes{get;set;} 
} 
class RoomType { 
    //other properties omitted for brevity 
    public List<Price> Prices {get;set;} 
} 
class Price { 
    //other properties omitted for brevity 
    decimal TotalPrice{get;set;} 
} 

的樣本,因此酒店的頂級其中有一些Rooms,其中有一些RoomTypes其中有一些Prices

我想簡單過濾掉任何東西比最便宜TotalPrice其他和與父母中的每個實例,但保持層次到位,留下一些酒店與客房,roomtypes和最小PRIC e

var filteredHotels = from hot in resp.Hotels 
       let types = hot.Rooms.SelectMany(rooms => rooms.RoomTypes) 
       let prices = types.SelectMany(t => t.Prices) 
       select new { 
        hot 
        , types 
        , minPrice = prices.Min(p => p.TotalPrice) 
       }; 

但當然這是行不通的。

響應意見,我需要在層次結構中的所有類的屬性。我基本上只想過濾出多個昂貴的價格。你可以認爲一個房間會有一個單一的價格,但每個房間可以有不同的設置,因此他們有不同的價格。加上它不是我的等級,我正在使用的一種服務.. 對不起,resp是服務的響應,其中包含酒店對象。 ,因此可以忽略不計..

所以要清楚(我希望),我需要的酒店對象,而且它下面的孩子的過濾列表離開我,下面有一個最廉價的TotalPrice .. 我希望以避免項目的層次結構,以得到我想要的所有屬性,但也許這是不可能不

感謝您的幫助

+0

爲什麼'Room'類沒有'Price'屬性。當然,單個房間必須有單一的價格? – gunr2171

+0

resp對象是什麼類型? –

+0

請在結果中添加您想要的屬性。它會更容易回答。 –

回答

0

將這樣的事情對你的工作?

var filteredHotels = resp.Hotels.Select(h => 
          h.Rooms.Select(r => 
          r.RoomTypes.Select(rt => 
          new 
          { 
           HotelName = h.Name, 
           RoomName = r.Name, 
           RoomTypeName = rt.Name, 
           MinPrice = rt.Prices.Min(p => p.TotalPrice) 
          }))); 

假設你所有的類都有Name屬性。你可以用你想要的任何東西來替換這個屬性。

class hotel 
{ 
    public string Name { get; set; } 
    //other properties omitted for brevity 
    public List<Room> Rooms { get; set; } 
} 
class Room 
{ 
    public string Name { get; set; } 
    //other properties omitted for brevity 
    public List<RoomType> RoomTypes { get; set; } 
} 
class RoomType 
{ 
    public string Name { get; set; } 
    //other properties omitted for brevity 
    public List<Price> Prices { get; set; } 
} 
class Price 
{ 
    public string Name { get; set; } 
    //other properties omitted for brevity 
    public decimal TotalPrice { get; set; } 
}