查找具有最大值属性的元素最快的方法 [英] What is faster in finding element with property of maximum value

查看:48
本文介绍了查找具有最大值属性的元素最快的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常用,要查找具有最大值属性的元素,我这样做

Commonly, to find element with property of max value I do like this

var itemWithMaxPropValue = collection.OrderByDescending(x => x.Property).First();

但是从性能角度来看,这是个好方法吗?也许我应该做这样的事情?

But is it good way from performance point of view? Maybe I should do something like this?

var maxValOfProperty = collection.Max(x => x.Property);
var itemWithMaxPropValue = collection
                                 .Where(x => x.Property == maxValueOfProperty).First();

推荐答案

两个解决方案都不是很有效.第一个解决方案涉及对整个集合进行排序.第二种解决方案需要遍历两次收集.但是您可以一次性查找具有最大属性值的项目,而无需对集合进行排序. MoreLINQ 库中有MaxBy扩展.或者,您可以实现相同的功能:

Both solutions are not very efficient. First solution involves sorting whole collection. Second solution requires traversing collection two times. But you can find item with max property value in one go without sorting collection. There is MaxBy extension in MoreLINQ library. Or you can implement same functionality:

public static TSource MaxBy<TSource, TProperty>(this IEnumerable<TSource> source,
    Func<TSource, TProperty> selector)
{
    // check args        

    using (var iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())            
            throw new InvalidOperationException();

        var max = iterator.Current; 
        var maxValue = selector(max);
        var comparer = Comparer<TProperty>.Default;

        while (iterator.MoveNext())
        {
            var current = iterator.Current;
            var currentValue = selector(current);

            if (comparer.Compare(currentValue, maxValue) > 0)
            {
                max = current;
                maxValue = currentValue;
            }
        }

        return max;
    }
}

用法很简单:

var itemWithMaxPropValue = collection.MaxBy(x => x.Property); 

这篇关于查找具有最大值属性的元素最快的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆