我需要对照数据表中的一组开始日期和结束日期检查用户输入的开始日期和结束日期,以确保没有重叠。
用户使用开始日期和结束日期组合请求休假。我想确保这个开始和结束日期不包含在我从数据库读取到数据表中的一组日期中。
我使用了以下内容,但不确定是否正确。这里的“表”包含用户从数据库中获取的现有休假请求,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;
}
如果返回的数据表中没有行,则可以,否则存在重叠。
答案 0 :(得分:0)
使用扩展方法检查日期是否在其他两个日期之间,
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()
并使其返回一个{{1} },指示是否存在任何重叠。