.net 在没有 for 循环的情况下为数据表中的所有行设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5063551/
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-09-03 15:17:57  来源:igfitidea点击:

Set value for all rows in a datatable without for loop

.netvb.netdatatablefor-loop

提问by Soham Dasgupta

I'm trying to set the same value for all rows for a single column in a datatable without using for loop. Can anyone suggest any faster methods to achieve the same.

我试图在不使用 for 循环的情况下为数据表中的单个列的所有行设置相同的值。任何人都可以建议任何更快的方法来实现相同的目标。

采纳答案by Marc Gravell

Not unless you count foreach. One way or another, you'll need to loop.

除非你数数foreach。一种或另一种方式,你需要循环。

If you use the DataTableversion, the fastest approach is to use the DataColumnaccessor, i.e.

如果使用DataTable版本,最快的方法是使用DataColumn访问器,即

var col = table.Columns["Foo"];
foreach(var row in table.Rows)
    row[col] = value;

As an alternative : since this presumably relates to a database, write the TSQL manually to set all the values appropriately (i.e. with a suitablewhereclause in the TSQL).

作为替代方案:因为这可能与数据库有关,请手动编写 TSQL 以适当地设置所有值(即在 TSQL 中使用合适的where子句)。

update [theTable]
set [theColumn] = theValue
where --TODO - something sensible

回答by Julian

yes, this is possible, even without loop! This can be done with Expressionproperty. Keep in mind that string values should be quoted, otherwise it sees this as another columnname.1

是的,这是可能的,即使没有循环!这可以通过Expression财产来完成。请记住,字符串值应该被引用,否则它会将其视为另一个列名。1

This will set the column 'col1' with the string value a:

这将使用字符串值设置列“col1” a

preview.Columns["col1"].Expression = "'a'";

This will display in 'col1' the value of the column 'col2':

这将在“col1”中显示“col2”列的值:

preview.Columns["col1"].Expression = "col2";

回答by Jonathan

Have you considered removing and re-adding the column with a default value?

您是否考虑过删除并重新添加具有默认值的列?

dt.Columns.Remove("FilterText")
dt.Columns.Add(New DataColumn() With {.ColumnName = "FilterText",
                                      .DataType = GetType(String),
                                      .DefaultValue = "Jam and chips"})

(assuming your column name is FilterText, and you want to set it to "Jam and chips")

(假设您的列名是 FilterText,并且您想将其设置为“果酱和薯条”)

回答by Sohaib Yahya

I ran in to this type of problem where the Select All Checkbox was used to set a column "sel" to 1 or 0, the foreach loop is very slow, I grabed the idea from @Jonathan answer which is more faster, but with some minor modification as the With clause do not work in c#

我遇到了这种类型的问题,其中使用 Select All Checkbox 将列“sel”设置为 1 或 0,foreach 循环非常慢,我从 @Jonathan 回答中获取了这个想法,它更快,但有一些小的修改,因为 With 子句在 c# 中不起作用

dtEmpList.Columns.Remove("sel");
dtEmpList.Columns.Add(new DataColumn("sel",typeof(bool)(chkSelectAll.Checked ? "1" : "0")));