首页 > 解决方案 > 使用自定义方法结合 Where 和 OrderByDescending

问题描述

我正在尝试使用自定义方法进行排序,但我也想使用相同的自定义方法仅返回与某个值匹配的结果。我意识到下面的代码有效,但我希望有一种方法可以将这两种方法结合起来,以希望加快这个过程。

public IEnumerable<List<decimal>> GetBestList(List<List<decimal>> inputList)
{
    var bestList = inputList.Where(x => x != null && CalculateAverage(x) > 0).
            OrderByDescending(x => CalculateAverage(x)));
            
    return bestList;
}

public decimal CalculateAverage(List<decimal> inputList)
{
    return inputList.Average();
}

标签: c#performancelinq

解决方案


据我了解,您希望防止重新计算平均值,因此您可以使用Select创建一个包含平均值和原始列表的临时元组,例如:

    public IEnumerable<List<decimal>> GetBestList(List<List<decimal>> inputList)
    {
        var bestList = inputList
            .Where(x => x != null )
            .Select(x => (x, Avg: CalculateAverage(x)))
            .Where(x => x.Avg > 0)
            .OrderByDescending(x => x.Avg)
            .Select(x => x.x);
        
        return bestList;
    }

推荐阅读