【问题标题】:Does DataView.RowFilter support 'between ... and ...'?DataView.RowFilter 是否支持“...和...之间”?
【发布时间】:2014-08-13 20:41:39
【问题描述】:

我要更改一个程序以根据一系列值过滤数据。

虽然效率不高,但信息会在指定的时间段内加载到内存中,并根据某些标准进行过滤以进行单独处理,例如生成 CSV 报告。

信息被加载到DataView,然后应根据正在处理的操作进行过滤。每三个进程处理这个DataView 的一个子集。然后,子集由过滤器通过DataView.RowFilter 属性确定。

根据我目前发现的情况,适用于RowFilterDataColumn.Expression 似乎充分利用了SQL where 子句语法,如下所示。

dataView.RowFilter = "Id = 999";
dataView.RowFilter = "Name like 'Stack%'"
dataView.RowFilter = "Id in (1, 2, 3, 10, 16, 34)"
dataView.RowFilter = "Amount < 5000"

如本文所述:DataView RowFilter Syntax [C#]

现在我想知道,由于存在难以测试的遗留代码,DataView.RowFilter 属性是否支持 SQL between 条件?

这是一个有效的DataColumn.Expression 以作为DataView.RowFilter 申请吗?

dataView.RowFilter = "Name = 'StackOverflow' and Amount between 5000 and 5999";

【问题讨论】:

    标签: .net expression dataview rowfilter datacolumn


    【解决方案1】:

    如果我没记错的话 Between 不支持,但为什么不简单:

    dataView.RowFilter = "Name = 'StackOverflow' and Amount >= 5000 and Amount <= 5999";
    

    MSDN:仅提及 Between 作为保留词,但在表达式中不受支持。

    我已经测试过了,使用BETWEEN 会抛出EvaluateException

    {"表达式包含不受支持的运算符'Between'。"}

    这是测试代码,示例数据:

    DataTable table = new DataTable();
    table.Columns.Add("Name");
    table.Columns.Add("Amount", typeof(int));
    table.Rows.Add("Site1", 1000);
    table.Rows.Add("OtherSite", 3000);
    table.Rows.Add("StackOverflow", 5100);
    table.Rows.Add("StackOverflow", 5500);
    table.Rows.Add("StackExchange", 5900);
    
    var dataView = table.DefaultView;
    

    首先,使用AND的有效表达式:

    dataView.RowFilter = "Name = 'StackOverflow' and Amount >= 5000 and Amount <= 5999";
    
    Console.Write("Count: {0}\r\nValues:\r\n{1}"
        , dataView.Count
        , string.Join(Environment.NewLine, dataView.Cast<DataRowView>() 
            .Select(o => string.Join(",", o.Row.ItemArray))));
    

    输出:

    Count: 2
    Values:
    StackOverflow,5100
    StackOverflow,5500
    

    现在使用BETWEEN的无效语法:

    dataView.RowFilter = "Name = 'StackOverflow' and Amount BETWEEN 5000 and 5999"; // boom
    

    【讨论】:

    • “为什么不简单地 [...]?”,仅仅是因为我更喜欢使用 between 语句,因为它更明显地表明它是一个单一字段的范围。我最终按照建议使用了and 比较。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多