views:

102

answers:

2

I would like to use the new Parallel.ForEach function to loop through a datatable 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 the error:

The type arguments for method 'System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable, System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

What is the correct syntax for this?

+5  A: 

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

Parallel.ForEach(dt.AsEnumerable(), drow =>
{
    ...
    Do Stuff
    ...
});
Jon Skeet
D'oh! Beat to the punch (by mere seconds)!
JaredReisinger
+1  A: 

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

... Parallel.ForEach(dt.AsEnumerable(), drow => ...
JaredReisinger

related questions