C# 获得最大值。对象列表中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14563527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:17:15  来源:igfitidea点击:

Get the max. value in List of objects

c#linq

提问by palak mehta

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 HotelRoomshas 10 items. I want to find the maximum value of AverageNightlyRate.

列表HotelRooms有 10 个项目。我想找到AverageNightlyRate的最大值 。

I am using for loop to iterate . Can I do it in an efficient manner ?

我正在使用 for 循环来迭代。我能以有效的方式做到这一点吗?

采纳答案by Sergey Berezovskiy

Use Enumerable.Max:

使用Enumerable.Max

var maxAverageRate = HotelRooms.Max(r => r.RoomPriceDetails.AverageNightlyRate)


If RoomPriceDetailscould be null, then:

如果RoomPriceDetails可以null,那么:

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

回答by Iswanto San

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

回答by clamchoda

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

使用Min()orMax()时最好记住,您的设计可能要考虑实现DefaultIfEmpty().If.Where子句消除了所有元素,我们将在调用or时收到“序列不包含元素”错误。Min()Max()

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

而不是直接在我们的Where语句返回的集合上调用 Min 或 Max ,我们可以Select()将我们感兴趣的属性列表。 然后我们可以滑入DefaultIfEmpty。调用Min()Max()DefaultIfEmpty确保我们收集与工作。

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.