Parallel forEach in DataTable

I would like to use the new Parallel.ForEach function to loop through the data and perform actions on each row. I am trying to convert the code below:

foreach(DataRow drow in dt.Rows) { ... Do Stuff ... } 

To this code:

  System.Threading.Tasks.Parallel.ForEach(dt.Rows, drow => { ... Do Stuff ... }); 

When I run the new code, I get an error message:

Type arguments to the method "System.Threading.Tasks.Parallel.ForEach (System.Collections.Generic.IEnumerable, System.Action)" cannot be taken out of use. Try explicitly specifying type arguments.

What is the correct syntax for this?

+41
parallel-processing
Aug 04 '10 at 18:25
source share
4 answers

DataTable.Rows returns a DataRowCollection , which implements only IEnumerable , not IEnumerable<DataRow> . Use the AsEnumerable() extension method of the DataTable (from DataTableExtensions ) instead:

 Parallel.ForEach(dt.AsEnumerable(), drow => { ... Do Stuff ... }); 
+88
Aug 04 '10 at 18:27
source share

Parallel.ForEach () expects the first argument to be an IEnumerable <> type. There is no DataTable.Rows, but you can turn it into one using the AsEnumerable () extension method. Try:

 ... Parallel.ForEach(dt.AsEnumerable(), drow => ... 
+7
Aug 04 '10 at 18:30
source share

This is better than the accepted answer because it does not need to reference System.Data.DataSetExtensions:

  Parallel.ForEach(dt.Rows.Cast<DataRow>(), dr => 

To use ForEach with an nonequivalent collection, you can use the Cast extension method to convert the collection to a common collection, as shown in this example.

+5
Oct. 12 '16 at 19:04
source share

I had to change Jon Skeet's answer to make it work.

 Parallel.ForEach(dt.AsEnumerable<DataRowType>(), drow => { drow.SomeCol = ""; }); 
0
Dec 13 '17 at 13:24
source share



All Articles