Search code examples
c#.netmultithreadingforeach.net-framework-version

How to convert foreach to Parallel.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 to a Parallel.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 does not contain StartsWith() extension method. How to solve it?


Solution

  • 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.