[英]Specified cast is not valid when filtering a DataTable where the column can be int32 or int64
因此,根據提供的列名和過濾器對數據表進行即時過濾。 我已將過濾器指定為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<Int64>(columnName)
區域中的異常
知道如何重寫它以支持DataTable中的Int32和Int64列類型嗎?
嘗試Convert.ToInt64
:
from myRow in dt.AsEnumerable()
where Convert.ToInt64(myRow[columnName]) == filter
select myRow
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.