使用linq和displing从数据表中选择多个列 [英] Selecting multiple columns from data table using linq and displing

查看:128
本文介绍了使用linq和displing从数据表中选择多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我可以使用Linq从数据表中选择多个不同的列。



Hi,

I am able to select multiple distinct columns from a data table using Linq.

var dsStatus = (from row in dsDefectLibary.Tables[0].AsEnumerable()
                                select new
                                {
                                    statusID = row.Field<int>("DefectStatusId")
                                    ,Status = row.Field<string>("DefectStatus")
                                }).Distinct();







但是使用foreach显示这些选定的值时会出现错误'指定的演员表是无效的。'






But while displaying those selected values using foreach is giving error as 'Specified cast is not valid.'

foreach(var row in dsStatus)
{
     Console.Writeline(row.statusID);
     Console.Writeline(row.Status);
}





请指导我。

谢谢。



Please guide me.
Thank you.

推荐答案

延迟Linq-Query的执行,直到你在foreach循环中迭代结果。请参阅: LINQ和延期执行 [ ^ ]



这意味着错误实际发生在查询的执行中,Console.Writeline对它没有任何问题。



我假设列 DefectStatusId 不是Int32类型(= int)。其他理论原因(但可能不太可能): DefectStatusId 对于某些记录为空或 DefectStatus 不属于Type字符串。



检查列的数据类型,如果 DefectStatusId 不是Int32而是Byte,Short( Int16)或Long(Int64)然后将 statusID = row.Field< int>(DefectStatusId)中的int更改为匹配的Type。如果你不能这样解决,试试这个: statusID = Convert.ToInt32(row [DefectStatusId])
The execution of your Linq-Query is deferred until you iterate over the results in the foreach-loop. See: LINQ and Deferred Execution[^]

That means that the error actually happens in the execution of the query, the Console.Writeline doesn't have any problem with it.

I assume that the column DefectStatusId is not of Type Int32 (= int). Other theoretical causes (but probably unlikely): DefectStatusId is null for some record(s) or DefectStatus is not of Type String.

Check the data type of your columns and if DefectStatusId isn't Int32 but Byte, Short (Int16) or Long (Int64) then change the "int" in statusID = row.Field<int>("DefectStatusId") to the matching Type. If you can't solve it this way, try this: statusID = Convert.ToInt32(row["DefectStatusId"])


这篇关于使用linq和displing从数据表中选择多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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