Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the max. value in List of objects

Tags:

c#

linq

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 ?

like image 555
palak mehta Avatar asked Jan 28 '13 13:01

palak mehta


People also ask

How will you get the max valued item of a list?

Use max() to Find Max Value in a List of Strings and Dictionaries. The function max() also provides support for a list of strings and dictionary data types in Python. The function max() will return the largest element, ordered by alphabet, for a list of strings.

Can we use MAX function in list in Python?

The Python max() function returns the largest value in an iterable, such as a list. If a list contains strings, the last item alphabetically is returned by max().

How do you find the maximum value of a list in a for loop?

Use temp variable and if statement to find the largest number in a list Python using for loop. Writing your own logic is easy, use temp variable to assign the first value of the list then swap it with the next large number.


1 Answers

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);
like image 135
Sergey Berezovskiy Avatar answered Sep 21 '22 20:09

Sergey Berezovskiy