Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 641
user1736332 Avatar asked Sep 04 '25 17:09

user1736332


1 Answers

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;
    });
like image 135
Tim Schmelter Avatar answered Sep 07 '25 12:09

Tim Schmelter