I have DataTable full of data, with 3 columns - col1
, col2
, and col3
.
I have to update data in col3
(set it to null
) when the value in col3
is greater than 1000 or less than -1000. I tried to iterate each row and check this condition, but it is too slow. How do I improve the speed?
Presuming that the type of the column is int
, you can use Linq
:
var rowsToUpdate = data.AsEnumerable()
.Where(r => r.Field<int?>("col3") > 1000 || r.Field<int?>("col3") < -1000);
foreach( DataRow row in rowsToUpdate )
row.SetField<int?>("col3", null);
The field methods support nullable types and the SetField
method allows to use null
.
A little bit micro-optimization, just because you have mentioned that it's too slow:
var rowsToUpdate = data.AsEnumerable()
.Where(r => {
var val = r.Field<int?>("col3") ?? 0;
return val > 1000 || val < -1000;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With