Soham Dasgupta Soham Dasgupta - 1 year ago 149 Question

Set value for all rows in a datatable without for loop

I'm trying to set the same value for all rows for a single column in a datatable without using for loop. Can anyone suggest any faster methods to achieve the same.

Answer Source

Not unless you count foreach. One way or another, you'll need to loop.

If you use the DataTable version, the fastest approach is to use the DataColumn accessor, i.e.

var col = table.Columns["Foo"];
foreach(var row in table.Rows)
    row[col] = value;

As an alternative : since this presumably relates to a database, write the TSQL manually to set all the values appropriately (i.e. with a suitable where clause in the TSQL).

update [theTable]
set [theColumn] = theValue
where --TODO - something sensible
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download