Home > database >  Find nearest Date in past
Find nearest Date in past

Time:01-04

I have a Service class. One of the fields is a collection of ServicePrice objects, which have a Price and СhangeDate field.

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

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

I need method to find the price of a service that was relevant at some point in time.

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

I was finding a solution using the LINQ MinBy function:

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

But this function will return the nearest date, but not necessarily from the past. It would be quite strange to get a price for a product from the future.

CodePudding user response:

I would handle this in two phases:

  • Filter out everything in the future (with respect to date)
  • Find the latest remaining change date
public int? GetPriceAtDate(DateTime date) =>
    ServicePrices
        .Where(sp => sp.ChangeDate <= date)
        .MaxBy(sp => sp.ChangeDate)?.Price;
  • Related