从数据库中恢复日期时使用func

时间:2018-03-07 09:52:29

标签: c#

我有一个从db检索时间戳间隔的方法,它看起来像这样:

public IEnumerable<DateTime> GetCurrentsFlagTimestampPoints(DateTime startDate, DateTime endDate)
{
    return currentsRepository.GetTimestampPoints(startDate, endDate).Select(timestamp => new DateTime(timestamp.Year, timestamp.Month, timestamp.Day)).Distinct();
}

但是现在我想以更通用的方式使用它,所以我想传递Func<>来描述生成的日期格式,这样一旦我想要返回

new DateTime(timestamp.Year, timestamp.Month, timestamp.Day)

一次

new DateTime(timestamp.Year, timestamp.Month, timestamp.Day, timestamp.Hour)

我可以使用某种重载来做到这一点,但这会改变某些方法的现有结构。

我不知道如何解决这个问题,是否可能?

编辑:

没有表达式,它的效果很好:

    public IEnumerable<DateTime> GetCurrentsFlagTimestampPoints(DateTime startDate, DateTime endDate, Func<DateTime, DateTime> dateTimeExpr)
    {
        return currentsRepository.GetTimestampPoints(startDate, endDate).Select(dateTimeExpr).Distinct();
    }

1 个答案:

答案 0 :(得分:1)

您需要传递Expression<Func<DateTime,DateTime>>作为参数:

public IEnumerable<DateTime> GetCurrentsFlagTimestampPoints(DateTime startDate, DateTime endDate, Expression<Func<DateTime, DateTime>> dateTimeExpr)
{
    return currentsRepository.GetTimestampPoints(startDate, endDate).Select(dateTimeExpr).Distinct();
}

Expression<Func<DateTime, Datetime>> f1 = timestamp => new DateTime(timestamp.Year, timestamp.Month, timestamp.Day);

Expression<Func<DateTime, Datetime>> f1 = timestamp => new DateTime(timestamp.Year, timestamp.Month, timestamp.Day, timestamp.Hour);

GetCurrentsFlagTimestampPoints(DateTime.Now, DateTime.Now, f1); // or f2