title: Using 'AsParallel()' / 'Parallel.ForEach()' guidelines?
body: <p>Looking for a little advice on leveraging <code>AsParallel()</code> or <code>Parallel.ForEach()</code> to speed this up.</p>
  
  <p>See the method I've got (simplified/bastardized for this example) below.</p>
  
  <p>It takes a list like "US, FR, APAC", where "APAC" is an alias for maybe 50 other "US, FR, JP, IT, GB" etc. countires. The method should take "US, FR, APAC", and convert it to a list of "US", "FR", plus all the countries that are in "APAC".</p>
  
  <pre><code>private IEnumerable&lt;string&gt; Countries (string[] countriesAndAliases)
  {
      var countries = new List&lt;string&gt;();
  
      foreach (var countryOrAlias in countriesAndAliases)
      {
          if (IsCountryNotAlias(countryOrAlias))
          {
              countries.Add(countryOrAlias);
          }
          else 
          {
              foreach (var aliasCountry in AliasCountryLists[countryOrAlias]) 
              {
                  countries.Add(aliasCountry);
              }
          }
      }
  
      return countries.Distinct();
  }
  </code></pre>
  
  <p>Is making this parallelized as simple as changing it to what's below? Is there more nuance to using <code>AsParallel()</code> than this? Should I be using <code>Parallel.ForEach()</code> instead of <code>foreach</code>? What rules of thumb should I use when parallelizing <code>foreach</code> loops?</p>
  
  <pre><code>private IEnumerable&lt;string&gt; Countries (string[] countriesAndAliases)
  {
      var countries = new List&lt;string&gt;();
  
      foreach (var countryOrAlias in countriesAndAliases.AsParallel())
      {
          if (IsCountryNotAlias(countryOrAlias))
          {
              countries.Add(countryOrAlias);
          }
          else 
          {
              foreach (var aliasCountry in AliasCountryLists[countryOrAlias].AsParallel()) 
              {
                  countries.Add(aliasCountry);
              }
          }
      }
  
      return countries.Distinct();
  }
  </code></pre>