Search code examples
c#parallel.foreach

How to use Parallel.ForEach to display the values of IDictionary?


I am a C# enthusiast and I am playing with Parallel.ForEach method. I am trying to display the environment variables on a given system using the following code:

IDictionary vars = Environment.GetEnvironmentVariables();

Parallel.ForEach(vars, (envVar) =>
{
   Console.WriteLine("{0} = {1}", envVar.Key, envVar.Value);
});

However I end up with this error:

Error 3 The type arguments for method 'System.Threading.Tasks.Parallel.ForEach<TSource>(System.Collections.Concurrent.OrderablePartitioner<TSource>, System.Action<TSource,System.Threading.Tasks.ParallelLoopState,long>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I am pretty sure I am missing a cast but whatever I tried I couldn't make it work. Can you help me out?


Solution

  • IDictionary.GetEnumerator() returns an IDictionaryEnumerator, which has a property Entry that returns the current element (both key and value) of type DictionaryEntry, so that's the type you are using:

        static void Main()
        {
            var envVars = Environment.GetEnvironmentVariables();
    
            Parallel.ForEach( envVars.Cast<DictionaryEntry>(), ev =>
                {
                    Console.WriteLine( "{0}: {1}", ev.Key, ev.Value );
                } );
    
            Console.ReadLine();
        }