我如何解决“:System.Invalidcastexception:指定的强制转换无效”在Linq C# [英] How Do I Solve ": System.Invalidcastexception: Specified Cast Is Not Valid" in Linq C#

查看:162
本文介绍了我如何解决“:System.Invalidcastexception:指定的强制转换无效”在Linq C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试选择记录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."

推荐答案

branchid是

- 不是int

- null。
"branchid" is either
- not an int
- null.


添加以下行并检查您获得的数据类型是什么类型

add below line and check what is the type you get as data type
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

Quote:

列数据类型是bigint。

column Datatype is bigint .



尝试 Int64


try with Int64

IEnumerable<DataRow> query1 = query.Where(p => p.Field<Int64>("branchid") == 1);


试试这个:

Try this:
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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆