peter peter - 19 days ago 8
C# Question

how to convert foreach to parrallel.foreach in c#

i have a foreach loop like shown below

ArrayList list;
list = ftp.GetFileList(remotepath<ftp://ftp.getfilelist(remotepath/>);

foreach (string item in list)
{
}


I converted in to foreach like shown below without luck

ArrayList list;
list = ftp.GetFileList(remotepath<ftp://ftp.getfilelist(remotepath/>);

Parallel.ForEach(list.ToArra(), item =>
{
if (item.StartsWith("GExport_") &&(!item.ToUpper().Contains("DUM")))
{
}


It throws error like item doesnot contain StartsWith() extension methods.How to solve it

Answer

This is because the foreach is converting the items in the ArrayList to string from an object. All the items in an ArrayList are object at compile time, and object doesn't have a method called StartsWith.

In this case:

foreach (string item in list)

item is converted into a string from object.

To do the same you will need to perform the conversion yourself e.g.

Parallel.ForEach(list.OfType<string>().ToArray(), item ....

Or .Cast<string> instead of OfType if you want to fail at runtime if there's a non-string instance in your list.

Alternatively use a generic list such as List<String> to avoid runtime casting.