user1736332
user1736332

Reputation: 713

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

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?

Upvotes: 4

Views: 4727

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460228

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

Upvotes: 6

Related Questions