0

I have the following code:

private int AllFeb(Forecast f, IRepository repository)
{
    return All(f, repository, f.Feb);
}

private int AllJan(Forecast f, IRepository repository)
{
    return All(f, repository, f.Jan);
}

private int All(Forecast f, IRepository repository, int callBk)
{
    var otherForecasts = repository.Query<Forecast>().Where(r => r.PersonId == f.PersonId);
    if (otherForecasts.Any())
    {
        return otherForecasts.Sum(r => r.Feb) + callBk;
    }
    return 0;
}

As you can see, I am trying to come up with a shared function that can be reused for every month. The issue is that I need the following line in the All method:

otherForecasts.Sum(r => r.Feb)

to be generic but I need the callback inside the Sum method to be passed from outside (since I don't want it to be hardcoded as r.Feb.

Is there any way to avoid having code duplication here?

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
leora
  • 188,729
  • 360
  • 878
  • 1,366

1 Answers1

3

Pass an Expression<Func<Forecast, int>> into the All() method.

private int AllFeb(Forecast f, IRepository repository)
{
    return All(f, repository, f.Feb, r => r.Feb);
}

private int AllJan(Forecast f, IRepository repository)
{
    return All(f, repository, f.Jan, r => r.Jan);
}

private int All(Forecast f, IRepository repository, int callBk, Expression<Func<Forecast, int>> projection)
{
    var otherForecasts = repository.Query<Forecast>().Where(r => r.PersonId == f.PersonId);
    if (otherForecasts.Any())
    {
        return otherForecasts.Sum(projection) + callBk;
    }
    return 0;
}
Damir Arh
  • 17,637
  • 2
  • 45
  • 83