有没有办法在以下 string
变量上使用 DataView
的 Rowfilter
属性?
public DataTable FilterByLatestDate(DataTable tbl, string date_asof)
{
DataView latest = tbl.DefaultView;
//latest.RowFilter = "[date]= '" + date_asof + "'" ; //
//latest.RowFilter = string.Format("[date]= '{0}'", date_asof); // alternative to messing around with quotes
DataTable last_tbl = latest.ToTable();
return last_tbl;
}
Ps:我只对涉及.Rowfilter
的建议感兴趣
最佳
最佳答案
当您在 RowFilter 中使用日期时,要使用的引号是 # 符号
latest.RowFilter = "[date]= #" + date_asof + "#" ;
但是 RowFilter 属性接受字符串,因此当您使用日期作为过滤器时,变量应以“MM/dd/yyyy”格式表示。
因此,如果您的字符串 date_asof
不是这种格式,那么此代码将无法正常工作。
我建议您将 DateTime 传递给您的函数并将其格式化为
public DataTable FilterByLatestDate(DataTable tbl, DateTime date_asof)
{
DataView latest = tbl.DefaultView;
latest.RowFilter = "[date]= #" + date_asof.ToString("MM/dd/yyyy") + "#";
return latest.ToTable();
}
关于c# - 在函数的字符串类型参数上使用 C# DataView.RowFilter 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38873448/