例外:指定的演员表无效。 [英] Exception: Specified cast is not valid.

查看:87
本文介绍了例外:指定的演员表无效。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好。



我有DataTable对象的列

bool,Bitmap,string,string,string,string。



我想使用Linq以便我可以在第一列(bool)上进行某种过滤。



以下是我使用的内容:



  var  qqq = row < span class =code-keyword> in  DataTable.AsEnumerable()
where row.Field< bool>(ColumnNames [ 1 ])。ToString()== false .ToString()
选择行;

foreach (DataRow dataRow in qqq.ToList())
{
dataRow.Delete();
}





然后我得到了我无法施放字段的异常,为什么会这样?

解决方案

C#数组是从零开始的,你告诉第一列是bool,所以你应该使用 ColumnNames [0] 而不是 ColumnNames [1]

 其中 row.Field< bool>(ColumnNames [ 0 ])。ToString()==  false  .ToString()


听起来你的 bool 列是可空的,并且包含一个空值。请尝试使用 .Field< bool?>(...)



此外,没有必要将 bool bool?转换为字符串,以将其与同一类型的其他值进行比较。

  var  qqq = row   DataTable.AsEnumerable( )
其中 row.Field< bool?> (ColumnNames [ 1 ])== false
选择行;





Nullable类型(C#编程指南) [ ^


Hello.

I have DataTable object with columns
bool, Bitmap, string, string, string, string.

I want to use Linq so that I could make some kind of filtering on the first column (bool).

Here is what I use:

var qqq = row in DataTable.AsEnumerable()
          where row.Field<bool>(ColumnNames[1]).ToString() == false.ToString()
          select row;

foreach (DataRow dataRow in qqq.ToList())
{
    dataRow.Delete();
}



Then I get the exception that I can't cast the field, why is that?

解决方案

C# arrays are zero-based, and you tell that the first column is a bool, so you should use ColumnNames[0] instead of ColumnNames[1]:

where row.Field<bool>(ColumnNames[0]).ToString() == false.ToString()


It sounds like your bool column is nullable, and contains a null value. Try using .Field<bool?>(...) instead.

Also, there's no need to convert a bool or bool? to a string to compare it with another value of the same type.

var qqq = row in DataTable.AsEnumerable()
          where row.Field<bool?>(ColumnNames[1]) == false
          select row;



Nullable Types (C# Programming Guide)[^]


这篇关于例外:指定的演员表无效。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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