日期从和到过滤

Date From and To filtering

上下文

所以我有一个用户将在两个日期之间活跃:

User.StartDate
User.EndDate

在此期间,用户可以选择执行哪些任务。

Task.StartDate
Task.EndDate

注意:其中每个的结束日期都可以为空。

如果用户没有定义 EndDate,则用户将始终处于活动状态并且永远不会离开。

如果任务没有结束日期,则任务将永远不会结束,并且始终可供在任务结束后开始的用户使用。

尝试在 C# 中找出一个漂亮的方法来获得过滤的 List<Task> 任务,其中用户处于活动状态,并且任务日期范围在该活动期间。

我的解决方案

到目前为止这是我想出的,有没有人建议更好?

/// <summary>
/// Filter a list of Task so only tasks falling between dates will be returned.
/// If toDateTime is not defined, then it's considered open ended
/// </summary>
/// <param name="tasks"></param>
/// <param name="fromDateTime"></param>
/// <param name="toDateTime"></param>
/// <returns>A filtered list of tasks</returns>
public List<Task> FilterRatesOnDates(
    List<Task> tasks,
    DateTime fromDateTime,
    DateTime? toDateTime)
{
    tasks = tasks.FindAll(p =>
        ((p.ToDate.HasValue && fromDateTime <= p.ToDate) 
             || !p.ToDate.HasValue)
             && 
         ((toDateTime.HasValue && toDateTime >= p.FromDate)
             || !toDateTime.HasValue)
    );

    return tasks;
}

我最近遇到了类似的问题,被介绍给Fowler's Range。尽管这些示例不是使用 C# 编写的,但它们很容易翻译。这是我的:

public interface IRange<T>
{
    T Start { get; }
    T End { get; }
    bool Includes(T value);
    bool Includes(IRange<T> range);
}

public class DateRange : IRange<DateTime>
{
    public DateRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }

    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public bool Includes(DateTime value)
    {
        return (Start <= value) && (value <= End);
    }

    public bool Includes(IRange<DateTime> range)
    {
        return (Start <= range.Start) && (range.End <= End);
    }
}

并使用如下:

DateRange range = new DateRange(firstDate, secondDate);
bool inRange = range.Includes(dateToTest);

对于您的情况,请检查两个任务日期是否在要求的范围内。