简体   繁体   English

根据LINQ中一个值的最小值或最大值进行选择

[英]Selecting according to a Min or Max on one value in LINQ

This is equivalent to a correlated subquery, where you want the row which has the biggest or smallest X (and not the biggest or smallest X itself). 这等效于相关子查询,在该子查询中,您需要具有最大X或最小X(而不是最大X或最小X本身)的行。 I've only been able to get it through sorting and picking the first item. 我只能通过排序和选择第一个项目来获得它。

public static TSource PickMin<TSource, TMin>(this IEnumerable<TSource> source, Func<TSource, TMin> selector) where TMin : IComparable<TMin>
{
    return source.OrderBy(selector).FirstOrDefault();
}

Which doesn't exactly sound like the most efficient approach. 听起来并不是最有效的方法。 I think there's a combination of .Contains and .Min which could accomplish this? 我认为.Contains.Min的组合可以实现此目的? Or is this as good as LINQ gets? 还是像LINQ一样好?

You can use aggregation, which is O(n) (and which is afair used behind the scene, when you call Min() , Max() , etc.): 您可以使用O(n)聚合(并且在调用Min()Max()等时在后台使用的聚合):

public static TSource PickMin<TSource, TMin>(this IEnumerable<TSource> source, Func<TSource, TMin> selector) where TMin : IComparable<TMin>
{
     var first = source.FirstOrDefault();
     return source.Aggregate(first, (min, current) => selector(current).CompareTo(selector(min)) < 0 ? current : min);
}

If you want it to throw exceptions on empty collections (instead of returning a default value), remove the first line. 如果希望它在空集合上引发异常(而不是返回默认值),请删除第一行。

There is no good way to do this directly in LINQ. 没有直接在LINQ中执行此操作的好方法。 What you could is to use MinBy() from MoreLINQ 什么你可以是使用MinBy()MoreLINQ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM