views:

141

answers:

1

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 is to replace the key with 1000 and leave the name as is.

+1  A: 

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 DataRows in the original _table.
If you don't want to modify the original _table, you can copy it by calling DataTable.Copy().

SLaks
Since var is of local use i need EnumerableRowCollection
Swetha
Later i have to apply some filter operation on DataViewGridView1.DataSource = query.AsDataView();GridView1.DataSource = _t;
Swetha
Then you can write `GridView1.DataSource = affectedRows.AsDataView();`.
SLaks
thanks now i am able to perform the task,thank for your code.
Swetha
sorry i saw your updated code late
Swetha
Then you should accept this answer by clicking the hollow check.
SLaks