问题描述
我正在尝试选择记录where branchid = 1来自DataTable使用Linq C#
我的代码:
I am trying to select the Record where branchid=1 From DataTable using Linq C#
My Code:
DataSet ds = new DataSet();
ds = obj.Bind(); //from database
DataSet ds1 = new DataSet();
DataTable dt = ds.Tables[0];
IEnumerable<DataRow> query = from element in dt.AsEnumerable()
select element;
IEnumerable<DataRow> query1 = query.Where(p => p.Field<int>("branchid") == 1);//error
DataTable dt1 = query1.CopyToDataTable<DataRow>();
ds1.Tables.Add(dt1);
从此我得到此错误
From this Im getting this Error
": System.InvalidCastException: Specified cast is not valid."
推荐答案
var type = dt.Columns["branchid"].DataType;
您需要将列强制转换为上述类型。你说它在数据库中是int,但在你的数据集中它可能是下面的一个
you need to cast the column to above type. You say it as int in the database but in your dataset it could be one of below
Int16
Int32
Int64
SByte
Single
UInt16
UInt32
UInt64
更好的调试并确认数据类型。
根据您的以下评论
Better you debug and confirm the data type.
as per your below comment
列数据类型是bigint。
column Datatype is bigint .
尝试 Int64
try with Int64
IEnumerable<DataRow> query1 = query.Where(p => p.Field<Int64>("branchid") == 1);
IEnumerable<DataRow> query = from element in dt.AsEnumerable()
where(element.Field<int>("branchid") == 1)
select new
{
Field1 = element.Field<int>("branchid"),
Field2 = element.Field<type>("otherfield")
};
记住:C#区分大小写!
branchid
与以下内容不同 BranchId
。
和......请阅读我对该问题的评论;)
Remeber: C# is case sensitive!branchid
is not the same as BranchId
.
And... Please, read my comment to the question ;)
这篇关于我如何解决“:System.Invalidcastexception:指定的强制转换无效”在Linq C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!