C# 无循环更新数据表中的多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18830113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:21:33  来源:igfitidea点击:

Update multiple rows in datatable without loop

c#asp.netdatatable

提问by k-s

I have two datatable with conditions in application and want some processing for multiple rows to update column value.

我在应用程序中有两个带有条件的数据表,并希望对多行进行一些处理以更新列值。

For example:

例如:

I have datatable1 with 10000 rows. I want to filter rows by datatable.select("condition") and as per condition, I want to update row values.

我有 10000 行的 datatable1。我想通过 datatable.select("condition") 过滤行,并且根据条件,我想更新行值。

If for any condition, I found 20 rows from datatable. I want to update those 20 records in one shot. Not in any loop. I have datarow array for those values to update in datable.

如果有任何条件,我从数据表中找到了 20 行。我想一口气更新这 20 条记录。不在任何循环中。我有这些值的数据行数组要在数据中更新。

采纳答案by Rajesh Subramanian

You can try out the following linq,

您可以尝试以下 linq,

DataTable recTable = new DataTable();

// do stuff to populate table

recTable.Select(string.Format("[code] = '{0}'", someName)).ToList<DataRow>().ForEach(r => r["Color"] = colorValue);

You can substitute your columns and values here...

您可以在此处替换您的列和值...

回答by sivabalan

To Update Row With Multiple Condition use This

要更新具有多个条件的行,请使用此

    datatable.Select(string.Format("[lineNo]='{0}' and [Position]>='{1}' ", lineNo, Position)).ToList<DataRow>().ForEach(r => r["Linetext"] ="Sample Text" );

回答by Sarath Avanavu

If you want to default a column value with abcuse Expression, then you could use the below code.

如果要abc使用 use Expression来默认列值,则可以使用以下代码。

dt.Columns.Add("ColumnName").Expression = "'abc'";

In case if you need to pass the value dynamically using a variable, you could use the below code.

如果您需要使用变量动态传递值,则可以使用以下代码。

string str = "abc";
dt.Columns.Add("ColumnName").Expression = "'" + str + "'";