簡體   English   中英

根據數據表中的日期范圍集檢查日期范圍

[英]Checking date range against set of date ranges in a data table

我需要對照數據表中的一組開始日期和結束日期檢查用戶輸入的開始日期和結束日期,以確保沒有重疊。

用戶使用開始日期和結束日期組合請求休假。 我想確保這個開始日期和結束日期不包含在我從數據庫讀入數據表的一組日期中。

我使用了以下內容,但不確定是否正確。 這里的“表”包含用戶從數據庫中獲取的現有休假請求,startDate和endDate是他/她所請求的。 數據表具有“ StartDate”和“ EndDate”列。

private DataTable FilterTable(DataTable table, DateTime startDate, DateTime endDate)
{
    var filteredRows =
        from row in table.Rows.OfType<DataRow>()
        where (DateTime)row["StartDate"] >= startDate
        where (DateTime)row["StartDate"] <= endDate
        select row;

    var filteredTable = table.Clone();
    filteredRows.ToList().ForEach(r => filteredTable.ImportRow(r));
    return filteredTable;
}

如果返回的數據表沒有行,則可以,否則存在重疊。

使用擴展方法檢查日期是否在其他兩個日期之間,

public static class DateTimeExt {
    public static bool Between(this DateTime aDate, DateTime start, DateTime end) => start <= aDate && aDate <= end;
}

您可以編寫一個Overlaps方法來確定兩個范圍是否重疊:

public static bool Overlaps(DateTime aPeriodStart, DateTime aPeriodEnd, DateTime bPeriodStart, DateTime bPeriodEnd)
    => aPeriodStart.Between(bPeriodStart, bPeriodEnd) ||
       aPeriodEnd.Between(bPeriodStart, bPeriodEnd) ||
       bPeriodStart.Between(aPeriodStart, aPeriodEnd);

現在有了另一個擴展方法,該方法將IEnumerable<DataRow>轉換為包含行的DataTable

public static class IEnumerableExt {
    public static DataTable ToDataTable(this IEnumerable<DataRow> src) {
        var ans = src.First().Table.Clone();
        foreach (var r in src)
            ans.ImportRow(r);
        return ans;
    }    
}

您的最終方法很簡單:

DataTable FilterTable(DataTable timeTable, DateTime startDate, DateTime endDate) =>
    timeTable.AsEnumerable().Where(period => Overlaps(period.Field<DateTime>("StartDate"), period.Field<DateTime>("EndDate"), startDate, endDate)).ToDataTable();

注:如果您不需要應答DataTable的話,這會更有效,以取代.ToDataTable().Any()只是有方法返回一個bool指示是否存在任何重疊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM