1

当我有一个 DataView 操作时

 EnumerableRowCollection<DataRow> query 
    = from order in _table.AsEnumerable()
      where order.Field<Int32>("key") > 2 && order.Field<Int32>("key") < 4
      select order.Field<Int32>("key")=1000, order.Field<string>("name");   

我无法形成上述表达式。

当我尝试

select new {key= 1000,name= order.Field<string>("name") };

我有

    Cannot implicitly convert type 
   'System.Data.EnumerableRowCollection<AnonymousType#1>'   
    to 'System.Data.EnumerableRowCollection<System.Data.DataRow>'

如何形成正确的查询?我的任务是用 1000 替换密钥并保持名称不变。

4

1 回答 1

1

当您编写时select new {key= 1000,name= order.Field<string>("name") },您正在创建一个与 . 无关的新匿名类型DataRow
因此,您不能将其分配给EnumerableRowCollection<DataRow>.

要修复编译器错误,请更改EnumerableRowCollection<DataRow>var.


但是,这并不能解决您的根本问题。
LINQ 不能用于修改数据。

您需要使用普通foreach循环并设置key值,如下所示:

var affectedRows = from order in _table.AsEnumerable()
  where order.Field<Int32>("key") > 2 && order.Field<Int32>("key") < 4
  select row;
foreach(DataRow row in affectedRows) {
    row["key"] = 1000;
}

这段代码会修改原来DataRow的 s 中的 s _table
如果不想修改原件_table,可以调用复制DataTable.Copy()

于 2010-07-18T18:57:20.187 回答