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

本文关键字:错误 DataTable LINQ 查询 检索 | 更新日期: 2023-09-27 18:04:36

问题1:

我正在写一个查询,以获得数据表中一行的索引:

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的对象。

我哪里错了?

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

只需为您需要的每个任务添加一个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"实际上是一个整数吗?