Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
488 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
    ...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...