使用自定义方法组合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();
}

据我所知,您希望防止重新计算平均值,因此可以使用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;
}

避免多次执行潜在的昂贵计算的方法是将序列投影到包括列表和计算的新值中。查询语法比方法语法更简单:

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

相关内容

  • 没有找到相关文章

最新更新