简体   繁体   中英

Update a DataTable in C# without using a loop?

Let suppose there are three columns in my DataTable

  1. code

  2. name

  3. color

If I know the code and name, how can I update the color of that specific row whose code and name match my criteria? I want to do this without using Loops!

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

With LINQ:

var dataRows = dt.AsEnumerable().Select(c => { c["color"] = c["Code"].ToString() == "1" ? "Red" : "White"; return c; });
dt = dataRows.CopyToDataTable();

You could do:

 foreach (DataRow row in datatable.Rows)
        {
            if(row["code"].ToString() == someCode && row["name"].ToString() == someName)

              {
                  row["color"] = someColor;
              }


        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM