Update multiple rows in datatable without loop
Asked Answered
F

4

2

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.

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.

Folberth answered 16/9, 2013 at 14:9 Comment(5)
How exactly do you want to update the rows? This seems like something you could probably do with a dynamic query using the in keyword.Lugubrious
How do you think you can do it without a loop? If framework provides some method also it will be internally doing a loop!Poorly
maybe he means with lambda expressions.. but there will be anyway a loopKitchen
@Sriram - Yes, I know but better way or anything or any method which I am not aware if! Thats the reason I posted question.Folberth
@Kitchen - Thanks for your understanding. Something similar I am looking for.Folberth
D
11

You can try out the following 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...

Dextrosinistral answered 16/9, 2013 at 14:16 Comment(4)
Loop is far far efficient than thisPoorly
this is just a way to update without using loops externally. if performance is a constraint, then go for Parallel For.Dextrosinistral
Thanks for inputs and suggestions.Folberth
string.Format("[Code]='{0}'",somename) what is code here and what is somename. are you updating the value of codeMakedamakefast
F
2

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" );
Forcier answered 20/8, 2014 at 7:48 Comment(1)
This is just a fancier way of still doing a loop - Note the 'ForEach(...)'Cichlid
D
0

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

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 + "'";
Drupe answered 28/3, 2017 at 17:27 Comment(0)
K
0

An example in VB.NET

dt.Select("id = 1").ToList().ForEach(Sub(drow) drow("val") = "number 1")
Karajan answered 4/7 at 0:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.