Get the max. value in List of objects
c#, linq
Solution
Use Enumerable.Max:
var maxAverageRate = HotelRooms.Max(r => r.RoomPriceDetails.AverageNightlyRate)
If `RoomPriceDetails` could be `null`, then:
var maxAverageRate = HotelRooms.Where(r => r.RoomPriceDetails != null)
.Max(r => r.RoomPriceDetails.AverageNightlyRate);
Or
var maxAverageRate = HotelRooms.Select(room => room.RoomPriceDetails)
.Where(price => price != null)
.Max(price => price.AverageNightlyRate);
Problem
I have the following classes. ``` public class PriceDetails { public float AverageNightlyRate { get; set; } } public class RoomContainer { public PriceDetails RoomPriceDetails { get; set; } public string PromotionDescription { get; set; } } public List<RoomContainer> HotelRooms { get; set; } ``` The list HotelRooms has 10 items. I want to find the maximum value of AverageNightlyRate. I am using for loop to iterate . Can I do it in an efficient manner ?