C# 使用自定义方法组合Where和OrderByDescending

C# 使用自定义方法组合Where和OrderByDescending,c#,performance,linq,C#,Performance,Linq,我尝试使用自定义方法进行排序,但我也希望使用相同的自定义方法只返回与特定值匹配的结果。我意识到下面的代码是有效的,但我希望有一种方法可以将这两种方法结合起来,从而加速这个过程 public IEnumerable<List<decimal>> GetBestList(List<List<decimal>> inputList) { var bestList = inputList.Where(x => x != null &&

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

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();
}
public IEnumerable GetBestList(列表输入列表)
{
var bestList=inputList.Where(x=>x!=null&&CalculateAverage(x)>0)。
OrderByDescending(x=>CalculateAverage(x));
返回最佳列表;
}
公共十进制计算范围(列表输入列表)
{
返回inputList.Average();
}

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

    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;
    }
public IEnumerable GetBestList(列表输入列表)
{
var bestList=inputList
.其中(x=>x!=null)
.选择(x=>(x,平均值:CalculateAverage(x)))
.其中(x=>x.Avg>0)
.OrderByDescending(x=>x.Avg)
.选择(x=>x.x);
返回最佳列表;
}

避免多次执行可能非常昂贵的计算的方法是将序列投影到一个新值中,该值包括列表和计算。使用查询语法比使用方法语法更简单、更容易:

public IEnumerable<List<decimal>> GetBestList(List<List<decimal>> inputList)
{
    var query = from list in inputList
                where list != null
                let average = CalculateAverage(list)
                where average > 0
                orderby average
                select list;
}
public IEnumerable GetBestList(列表输入列表)
{
var query=来自inputList中的列表
where list!=null
让平均值=计算平均值(列表)
其中平均值>0
平均订购量
选择列表;
}

为什么您认为结合这些方法可以提高速度?为什么你认为加快计算速度很重要?@NetMage只是想避免多次运行相同的计算请注意,
let
除了使用匿名对象而不是值元组外,还会执行类似的操作。