简体   繁体   English

在不使用循环的情况下更新 C# 中的数据表?

[英]Update a DataTable in C# without using a loop?

Let suppose there are three columns in my DataTable假设我的 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:您可以使用 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.

相关问题 如何在没有for每个循环的情况下在C#中更新DataTable? - How to Update DataTable in C# without For Each Loop? 更改数据表列中的DATETIME格式而不在C#中使用循环 - Changing DATETIME format in datatable column without using loop in C# 使用Linq不循环更新同一数据表 - update same datatable using Linq without loop 最快的方式来更新所有行,使其在datatable中的一列中具有相同的值,而不在C#中进行循环 - Fastest way to update all rows to have same value in one column in datatable, without loop in C# 使用DataTable进行循环的C#启用按钮 - C# enabling button using datatable for loop 使用OleDbDataAdapter更新数据表C# - Using OleDbDataAdapter to update a DataTable C# 如何在不使用C#中的for或foreach循环的情况下使用datatable从特定的mysql表中获取每个值? - How to get each value from a particular mysql table by using datatable without using a for or foreach loop in c#? 在不使用For循环的情况下,使用C#中的dataTable中的ID更新数据库(SQL Server) - Updating a DB (SQL Server) using Ids from a dataTable in C# without For loop 在C#中循环遍历DataTable并更新变量 - Loop through rows DataTable in C# and update variables C#DataTable-如何在没有for循环的情况下将列设置为value? - C# DataTable - How to set a column to value without for loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM