在不使用循环的情况下更新C#中的DataTable
本文关键字:更新 中的 DataTable 情况下 循环 | 更新日期: 2023-09-27 17:57:31
假设我的DataTable 中有三列
-
代码
-
名称
-
彩色
如果我知道代码和名称,我如何更新代码和名称符合我的条件的特定行的颜色?我想在不使用循环的情况下执行
您可以使用LINQ:
DataRow dr = datatable.AsEnumerable().Where(r => ((string)r["code"]).Equals(someCode) && ((string)r["name"]).Equals(someName)).First();
dr["color"] = someColor;
当然,我假设所有这些标准都是字符串。您应该将强制转换更改为正确的类型。
// 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);
使用LINQ:
var dataRows = dt.AsEnumerable().Select(c => { c["color"] = c["Code"].ToString() == "1" ? "Red" : "White"; return c; });
dt = dataRows.CopyToDataTable();
你可以做:
foreach (DataRow row in datatable.Rows)
{
if(row["code"].ToString() == someCode && row["name"].ToString() == someName)
{
row["color"] = someColor;
}
}