例外:指定的演员表无效。 [英] Exception: Specified cast is not valid.
本文介绍了例外:指定的演员表无效。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好。
我有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
选择行;
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 useColumnNames[0]
instead ofColumnNames[1]
:
where row.Field<bool>(ColumnNames[0]).ToString() == false.ToString()
It sounds like yourbool
column is nullable, and contains a null value. Try using.Field<bool?>(...)
instead.
Also, there's no need to convert abool
orbool?
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;
这篇关于例外:指定的演员表无效。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文