c# - 在函数的字符串类型参数上使用 C# DataView.RowFilter 属性

标签 c#

有没有办法在以下 string 变量上使用 DataViewRowfilter 属性?

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/

相关文章:

c# - Microsoft.Interop 对象不会退出或 "release"

c# - 调试时Epplus Save()、SaveAs()等方法运行非常慢

c# - 使用 Fopen 在 C 中读取文件并从中获取特定值

c# - asp.net datagrid findcontrol 为文本框返回 null

c# - 基于CPU架构的dll后期绑定(bind)

c# - NetFramework 应用程序在同一解决方案中引用 NetFramework 库,在另一个解决方案中引用 NetStandard 库。 : could not load file or assembly

c# - 将可空值列表转换为对象列表

c# - 在什么时候我需要处理我的自定义 WPF 用户控件?

c# - 哪一个是最好的方法 Const 或 Resources(resx)

c# - 在 C# 中遍历 windows 文件系统中文件的权限