c# - 查找过去最近的日期

我有一个 Service 类。其中一个字段是 ServicePrice 对象的集合,它有一个 PriceСhangeDate 字段。

class Service 
{
    ObservableCollection<ServicePrice> ServicePrices {get; set;}
    // other fields
}

class ServicePrice 
{
    int Price {get;set;}
    DateTime ChangeDate {get;set;}
}

我需要找到某个时间点相关服务价格的方法。

 public int? GetPriceAtDate(DateTime date)
{
    // Do something here
    int? ActualPrice = 0 
    return ActualPrice;
}

我正在寻找使用 LINQ MinBy 函数的解决方案:

 public int? GetPriceAtDate(DateTime date)
{
    return ServicePrices.MinBy(sp => (sp.ChangeDate - date).Duration()).Price;
}

但此函数将返回最近的日期,但不一定是过去的日期。从 future 获得产品的价格会很奇怪。

最佳答案

我会分两个阶段处理:

  • 过滤掉 future 的一切(关于date)
  • 查找最新的剩余更改日期
public int? GetPriceAtDate(DateTime date) =>
    ServicePrices
        .Where(sp => sp.ChangeDate <= date)
        .MaxBy(sp => sp.ChangeDate)?.Price;

https://stackoverflow.com/questions/74996814/

相关文章:

powershell - 如何在 PowerShell 方法链接中使用换行符

regex - Linux 提取特定字符串之间的文本

arrays - 如何将数组的元素移动到数组的开头

python - 什么时候值得在 if-else 语句上使用循环?

c# - C# 是否有某种 value_or_execute 或 value_or_throw?

haskell - 减少围绕手工包装的 `Num` 类型的样板

c# - Blazor (.net 7) 中的三种依赖注入(inject)语法有区别吗?

LUA - 表中最常见的项目

javascript - 使用 js 正则表达式验证 gsheet/excel 相对范围字符串

r - 如何将整行作为列名?