palak mehta
palak mehta

Reputation: 706

Get the max. value in List of objects

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 ?

Upvotes: 8

Views: 59554

Answers (3)

clamchoda
clamchoda

Reputation: 4951

When using Min() or Max()it is good to keep in mind that your design may want to consider implementing DefaultIfEmpty(). If the .Where clause eliminates all elements we'll receive 'Sequence contains no elements' error when calling Min() or Max().

Instead of calling Min or Max directly on the collection returned by our Where statement, we can Select() the property list we are interested in. Then we can slip in DefaultIfEmpty. Calling Min() or Max() on DefaultIfEmpty ensures us a collection to work with.

var maxRate = HotelRooms.Where(r => r.RoomPriceDetails != null)
                        .Select(r => r.RoomPriceDetails.AverageNightlyRate)
                        .DefaultIfEmpty() // Now even if our where causes an empty selection list we will return DefaultIfEmpty.
                        .Max(); // Now we always have a gaurenteed value for max.

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

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);

Upvotes: 24

Iswanto San
Iswanto San

Reputation: 18569

HotelRooms.Max (r => r.RoomPriceDetails.AverageNightlyRate );

Upvotes: 3

Related Questions