c# - 使用自定义方法结合 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;
}
推荐阅读
- django - 及时发送错误的邮件
- logstash - 在 ELK 堆栈中使用 filebeat 和 logstash 从多个服务器获取日志的任何推荐想法?
- amazon-web-services - 如何使用 HTTP 代理集成配置 AWS apigateway 代理资源?
- java - 正则表达式 Java - 如何检查值之间是否不存在逗号字符?
- python - 在模式弹出窗口中提交 django 表单
- java - 如何在 Spring Data MongoDB 的 ProjectionOperation 中投影 map 和 reduce?
- javascript - 在不使用填充的情况下向 Material UI Grid 添加一个空白列
- git - 克隆 git 存储库时出现 SSL 证书错误
- amazon-web-services - 当 SQS 消息发送到死信队列时如何生成警报?
- jenkins-pipeline - Cloudbees Jenkins:在不同的 Jenkins 实例之间触发下游作业