ASP.net LINQ on DataView
When i have a DataView Operation as
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");
I can't form the above expression.
When i try
select new {key= 1000,name= order.Field<string>("name") };
i got
Cannot implicitly convert type
'System.Data.EnumerableRowCollection<AnonymousType#1>'
to 'System.Data.EnumerableRowCollection<System.Data.DataRow>'
How to form the right query? My task开发者_如何学Python is to replace the key with 1000 and leave the name as is.
When you write select new {key= 1000,name= order.Field<string>("name") }
, you're creating a new anonymous type that has nothing to do with DataRow
.
Therefore, you can't assign it to a EnumerableRowCollection<DataRow>
.
To fix the compiler error, change EnumerableRowCollection<DataRow>
to var
.
However, that won't fix your underlying problem.
LINQ cannot be used to modify data.
You need to use a normal foreach
loop and set the key
values, like this:
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;
}
This code will modify the original DataRow
s in the original _table
.
If you don't want to modify the original _table
, you can copy it by calling DataTable.Copy()
.
精彩评论