[英]Update a DataTable in C# without using a loop?
Let suppose there are three columns in my DataTable假设我的 DataTable 中有三列
code代码
name姓名
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:您可以使用 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:使用 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.