从DataTable LINQ查询中检索列值时发生错误

时间:2014-05-22 03:35:38

标签: c# linq

问题1:

我正在编写一个查询来获取DataTable中行的索引:

var index = from row in DataTable1.AsEnumerable()
let r = row.Field<string>("Column1") 
where r == strColumn1 
select DataTable1.Rows.IndexOf(row);

然后我尝试为多列

做这件事
var index = from row in DataTable1.AsEnumerable()
let r = row.Field<string>("Column1") && s = row.Field<int>("Column2")
&& t = row.Field<string>("Column3") && u = row.Field<string>("Column4")
where r == strColumn1 && s == intColumn2 && t == strColumn3 && u == strColumn4
select DataTable1.Rows.IndexOf(row);

有可能吗?

问题2:

来自@DominicZukiewicz的答案在这样的多列上使用let时,我收到错误:

var index = from row in DataTable1.AsEnumerable()
let r = row.Field<string>("Column1")
let s = row.Field<int>("Column2")
let t = row.Field<string>("Column3")
let u = row.Field<string>("Column4")
where r == strColumn1 && s == intColumn2 && t == strColumn3 && u == strColumn4
select DataTable1.Rows.IndexOf(row);

DataTable1.Rows[index]["Columnx"] = intUpdateValueColumnx;
DataTable1.Rows[index]["Columny"] = intUpdateValueColumny;
DataTable1.Rows[index]["Columnz"] = intUpdateValueColumnz;
DataTable1.AcceptChanges();

这是以下形式出现的:

  

附加信息:无法将类型为'System.Data.EnumerableRowCollection`1 [System.Int32]'的对象强制转换为'System.IConvertible'。

我哪里错了?

1 个答案:

答案 0 :(得分:0)

只需为您需要的每项作业添加let

var index = from row in DataTable1.AsEnumerable()
   let r = row.Field<string>("Column1")
   let s = row.Field<int>("Column2")
   let t = row.Field<string>("Column3")
   let u = row.Field<string>("Column4")
   where r == strColumn1 && s == intColumn2 && t == strColumn3 && u == strColumn4
   select DataTable1.Rows.IndexOf(row);

-

当您更新了问题后,我会相应更新我的答案:

错误看起来转换s参数时出现问题,因为它无法将其转换为System.Int32

你确定“Column2”实际上是一个整数吗?