开发者

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 ca开发者_Python百科n 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;
              }


        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜