Set value for all rows in a datatable without for loop

≡放荡痞女 提交于 2020-01-27 07:42:12

问题


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.


回答1:


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

If you use the DataTable version, the fastest approach is to use the DataColumn accessor, i.e.

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 suitable where clause in the TSQL).

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



回答2:


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

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

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

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

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



回答3:


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")




回答4:


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#

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


来源:https://stackoverflow.com/questions/5063551/set-value-for-all-rows-in-a-datatable-without-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!