我在尝试使用 foreach 构造中的 var 变量循环查询对象时遇到错误。出于明确的原因,我将 xml 加载到数据集并执行 Dataset to Linq。请纠正我的错误。这是我的代码:
ds.ReadXml(fsReadXml);
DataTable myDataTable = ds.Tables[0];
var ordersQuery = myDataTable.AsEnumerable();
var subQuery = (from Geo03 in ordersQuery
select new
{
PARENTTYPE = Geo03.Field<String>("PARENTTYPE"),
PARENTINSTANCE = Geo03.Field<int>("PARENTINSTANCE"),
CHILDTYPE = Geo03.Field<String>("CHILDTYPE"),
CHILDINSTANCE = Geo03.Field<String>("CHILDINSTANCE"),
CHILDPOS = Convert.ToInt32(Geo03.Field<int>("CHILDPOS"))
});
XDocument doc = null;
foreach (var cin in subQuery)
{
}
这是生成的错误:
System.InvalidCastException: Specified cast is not valid.
at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
at SpectraWorkon.Program.<Main>b__0(DataRow Geo03) in c:\users\arun\documents\visual studio 2010\Projects\SpectraWorkon\SpectraWorkon\Program.cs:line 29
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at SpectraWorkon.Program.Main(String[] args) in c:\users\arun\documents\visual studio 2010\Projects\SpectraWorkon\SpectraWorkon\Program.cs:line 38
我收到这条线的错误 foreach (var cin in subQuery)
,说它无法投射。