2

是否可以使用 linq 创建查询以从用作分隔符的两个日期之间获取一系列值?

前任。

获取在 12/12/12 和 12/12/13 之间具有 Date 列值的所有实体。

我只是在寻找提示或方法。

4

3 回答 3

7

Of course you can, there is no "between" syntax if that's what you are getting at but it's relatively simple to do e.g.

list.Where(x => x.Date >= StartDate && x.Date <= EndDate);

If you want better readability, you could even write an extension method for DateTime i.e.

public static class DateTimeHelpers
{
    public static bool Between(this DateTime dateTime, DateTime startDate, DateTime endDate)
    {
        return dateTime >= startDate && dateTime <= endDate;
    }
}
...
list.Where(x => x.Date.Between(StartDate, EndDate));
于 2013-11-13T11:28:35.993 回答
1
public IEnumerable<DateTime> test(DateTime dt, DateTime dt2)
{
    // check if dt is smaller (or the same) as dt2 and code this out or throw error

    // replace dates with actual class / code
    List<DateTime> dates = new List<DateTime>();

    return dates.Where(d => d >= dt && d <= dt2);
}
于 2013-11-13T11:31:46.837 回答
1
var stuffBetweenDates = ListOfStuff.Where(c => c.Date >= 12/12/12 && c.Date <= 12/12/13);

我认为是这样的。显然,在我放置 12/12/12 和 12/12/13 的地方,您需要在这些地方放置公认的日期类型。

于 2013-11-13T11:29:35.920 回答