4

是否可以在 Linq to SQL 的 SQL 中执行此操作?

Select field from table where date between '2010-01-01' and '2010-01-31';

我意识到我可以做到:

where (monthBeginDate < a.StopDateActual && a.StopDateActual < monthEndDate)

但我很好奇我能不能做到前者。我有一个坏习惯,就是在这样的陈述上搞砸小于和大于。

4

2 回答 2

5

您可以执行以下操作:

public bool Between(DateTime value, DateTime from, DateTime To) {
   return value > from && value < to;
}

where Between(a.StopDateActual, monthBeginDate, monthEndDate)

但是,您应该注意,这适用于IEnumerable而不适用于IQueryable,即结果将在应用 where 之前从数据源中提取。在大量数据的情况下,这可能是一个性能问题,因此,你的 where 子句是你能做的最好的......只要小心 > 和 < !!!

于 2010-02-25T20:02:45.907 回答
4

不,这就是这样做的方法。我相信 C# 没有 between 运算符。

您总是可以像我一样作弊并编写扩展方法:

public static bool BetweenDates (this DateTime checker, DateTime floor, DateTime ceiling)
{
    return (checker <= ceiling) && (checker >= floor);
}

然后你可以这样做;-)

.Where(s => s.StopDateActual.BetweenDates(monthBeginDate, monthEndDate));
于 2010-02-25T19:53:12.897 回答