What is the fastest way to conditionally update data in a DataTable?

c#, conditional-statements, datatable, updates

Solution

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;
    });

Problem

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?

Original source