[英]How to change the DataTable Column Value without looping?
I have a DataTable which has 4 columns. 我有一个有4列的DataTable。 I want to change the 3rd column's value as "0". 我想将第3列的值更改为“0”。 Below is my DataTable. 下面是我的DataTable。
ID Name Value Type
---- ---- ----- -----
1 Sam 250 2
2 Rai 324 3
3 Tim 985 8
My Desired Result should be like below: 我想要的结果如下:
ID Name Value Type
---- ---- ----- ------
1 Sam 0 2
2 Rai 0 3
3 Tim 0 8
How to achieve this without looping? 如何实现这一点而不循环? Any suggestions please. 请给我任何建议。
How about this? 这个怎么样? ↓ without loop.... ↓没有循环....
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Rows.Add(new object[] { "1", "1" });
table.Rows.Add(new object[] { "1", "1" });
table.Rows.Add(new object[] { "1", "1" });
table.Rows.Add(new object[] { "1", "1" });
foreach (DataRow row in table.Rows)
Console.WriteLine(row["col2"].ToString());
Console.WriteLine("***************************************");
DataColumn dc = new DataColumn("col2");
dc.DataType = typeof(int);
dc.DefaultValue = 0;
table.Columns.Remove("col2");
table.Columns.Add(dc);
foreach (DataRow row in table.Rows)
Console.WriteLine(row["col2"].ToString());
Console.ReadKey();
}
You can use a simple trick here. 你可以在这里使用一个简单的技巧。 Delete row and re-add it to the table. 删除行并将其重新添加到表中。
dt.Columns.Remove("Value");
dt.Columns.Add("Value", type(System.Int32), 0);
DataRow[] rows = myDataTable.Select("id = 'myIdValue');
//If you don't want to select a specific id ignore the parameter for select.
for(int i = 0; i < rows.Length; i ++)
{
rows[i]["value"] = 0;
}
if you know the ID you can simply filter for it using Select or Find (not remember exactly but I think is Select), once you have the row, you can assign column values. 如果您知道ID,您只需使用选择或查找过滤它(不记得确切,但我认为是选择),一旦有了行,您就可以分配列值。
I am sure there is also a better LINQ oriented way but this old school ADO.NET/System.Data approach should work anyway. 我相信还有更好的面向LINQ的方式,但这个老式的ADO.NET / System.Data方法应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.