我有一个包含以下列的DataTable:
| ID |客户编号|付款金额| NextScheduleDate |
所有列均包含字符串值(例如, NextScheduleDate 的第0行单元格可能是字符串“ 11/1/2020”)。 我想对其进行过滤,并创建一个仅由 NextScheduleDate 值落在日期范围内的行组成的新DataTable。因此,用户选择范围,该方法应相应地过滤表。 NextScheduleDate 某些单元格值可能为null。 我对Linq还是很陌生,因此非常感谢您提供的所有帮助。到目前为止,这是我的方法,根本无法使用。
protected void LoadPayments()
{
// User provides textbox values
string startDate = txtStartDateRange.Text;
string endDate = txtEndDateRange.Text;
// This methods gets ALL payments, some of which have already happened
// and some of which are scheduled as future payments
DataTable tblPayments = Payments.GetAllRecurringPayments();
// We only want payments where the NextScheduleDate column value is the range selected by the user
// How to filter so that NextScheduleDate is in between startDate and endDate?
// (Needs to return values where startDate > NextScheduleDate > endDate
DataTable futurePayments = tblPayments.AsEnumerable()
.Where(r => r.Field<string>("NextScheduleDate") == ?????)
.CopyToDataTable();
// Bind
grdPayments.DataSource = futurePayments;
grdPayments.DataBind();
}
答案 0 :(得分:0)
我按原样显示以下代码,但尚未运行。我指出了代码可能在何处中断以及在哪种情况下。
为清楚起见,我假设可以使用Parse方法将您提供的日期转换为DateTime。如果不能,则推理仍然有效,只有您将使用TryParse并为日期无效的情况提供逻辑。
此外,我假设当日期字段的内容为空时,您的数据库返回DBNull.Value。
protected void LoadPayments()
{
// User provides textbox values
string startDate = txtStartDateRange.Text;
string endDate = txtEndDateRange.Text;
// Converts dates to DateTime (breaks if Dates are not valid)
DateTime s = DateTime.Parse(startDate);
DateTime e = DateTime.Parse(endDate);
// This methods gets ALL payments, some of which have already happened
// and some of which are scheduled as future payments
DataTable tblPayments = Payments.GetAllRecurringPayments();
// We only want payments where the NextScheduleDate column value is the range selected by the user
// How to filter so that NextScheduleDate is in between startDate and endDate?
// (Needs to return values where startDate > NextScheduleDate > endDate
DataTable futurePayments = tblPayments.AsEnumerable()
.Where(r =>
{
// Excludes if there is no date.
// Assumes the DB returns DBNull.Value if the Field is null
if (r.Field("NextScheduleDate") == DBNull.Value) { return false; }
// Breaks if Date is not valid
DateTime d = DateTime.Parse(r.Field<string>("NextScheduleDate"));
if (d < s) { return false; }
if (d > e) { return false; }
return true;
});
.CopyToDataTable();
// Bind
grdPayments.DataSource = futurePayments;
grdPayments.DataBind();
}