【问题标题】:Specified cast is not valid when filtering a DataTable where the column can be int32 or int64过滤列可以是 int32 或 int64 的 DataTable 时,指定的转换无效
【发布时间】:2014-07-18 08:39:21
【问题描述】:

所以我根据提供的列名和过滤器过滤 DataTable。 我已将过滤器指定为 Int64,以便它可以同时支持 Int32 和 Int64 过滤器值。

下面是我用来执行过滤的代码。

private DataTable FilterDataTableByInt(DataTable dt, string columnName, Int64 filter)
{
    DataTable Newdt = new DataTable();

    if (dt != null && dt.Rows.Count > 0)
    {
        var result = (from myRow in dt.AsEnumerable()
                      where myRow.Field<Int64>(columnName) == filter
                      select myRow);

        Newdt = result.AsDataView().ToTable();
    }

    return Newdt;
}

现在,当 im 过滤的列是 Int64 值时,这可以正常工作。但是,如果列是 Int32,我会得到强制转换异常。它在myRow.Field&lt;Int64&gt;(columnName)区域内例外

知道如何重写它以支持 DataTable 中的 Int32 和 Int64 列类型吗?

【问题讨论】:

    标签: c# linq casting datatable


    【解决方案1】:

    试试Convert.ToInt64:

    from myRow in dt.AsEnumerable()
    where Convert.ToInt64(myRow[columnName]) == filter
    select myRow
    

    【讨论】:

    • 酷。完美运行。
    猜你喜欢
    • 2012-04-24
    • 2021-09-27
    • 2014-07-19
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 2016-05-24
    • 2018-11-30
    相关资源
    最近更新 更多