Update a DataTable in C# without using a loop?

You can use LINQ:

DataRow dr = datatable.AsEnumerable().Where(r => ((string)r["code"]).Equals(someCode) && ((string)r["name"]).Equals(someName)).First();
dr["color"] = someColor;

Of course I'm assuming all those criteria are strings. You should change the casts to the correct types.


// Use the Select method to find all rows matching the name and code.
DataRow[] rows = myDataTable.Select("name 'nameValue' AND code = 'codeValue');

for(int i = 0; i < rows.Length; i ++)
{
      rows[i]["color"] = colorValue;
}

DataTable recTable = new DataTable();

// do stuff to populate table

recTable.Select(string.Format("[code] = '{0}' and [name] = '{1}'", someCode, someName)).ToList<DataRow>().ForEach(r => r["Color"] = colorValue);

Tags:

C#

.Net

Datatable