Dictionary foreach loop with multiple occurences A little look on what are Dictionaries:

dictWordCounter&lt;string, int&gt; 
dictWordPercent&lt;string, double&gt;
topTwentySeven&lt;string, double&gt;



WordCounter is the number of words. For example, if the word frog is 10 times it will be {frog, 10}.
WordPercent is the percent after some math in the program. For example, frog could be {frog, 0,55}.
topTwentySeven is the top 27 values from the WordPercent dictionary that I want to operate on.


So, I need to count something like this: 


If a word is just one, count it normally
If a word is twice or more, count it x2
Total number of words (after x2) must be still 27, not more


For example if it was "topThree" and words:

{Frog, 2}, {Monkey, 1}, {Giraffee, 1}, and their values from Percent Dictionary would be {Frog, 0,1}, {Giraffee, 0,2}, {Monkey, 0,45}, I want to count: 0,1*0,1*0,2 and (1-0,1) * (1-0,1)*(1-0,2).

Could someone look on this and check if it can be improved?

   var topTwentySeven = dictWordPercent.OrderByDescending(kvp =&gt; Math.Abs(kvp.Value - 0.5))
        .Take(27)
        .ToDictionary(kvp =&gt; kvp.Key, kvp =&gt; kvp.Value);

    int compare = 0;
    double temp2 = 1.0, A = 1.0, B = 1.0;
    for (int counter = 0; counter &lt; 27; )
    {               

        foreach (var word in topTwentySeven)
        {
        dictWordCounter.TryGetValue(word.Key, out compare);
            if (compare &gt;= 2 &amp;&amp; counter &lt; 26)
            {
                temp = word.Value;
                temp2 = temp * temp;
                A *= temp2;
                B *= (1 - temp2);
                counter = counter + 2;

            }
            else if (compare == 1 &amp;&amp; counter &lt; 27)
            {
                temp = word.Value;
                A *= temp;
                B *= (1 - temp);
                counter = counter + 1;
            }
            else if (counter &gt;= 27)
            {
                //Do nothing
            }
        }
    }

int top27C = topTwentySeven.Count();

double aN = 0.0, bN = 0.0;
aN = Math.Pow(A, (1 / top27C));
bN = Math.Pow(B, (1 / top27C));


I need both A and B.

totalSum = Math.Round(((aN / (aN + bN)) * 100), 2);
Don't write dead code - it rots like a corpse and makes it hard to maintain your code:


else if (counter &gt;= 27)
{
    //Do nothing
}



Just delete this.



You can use the ++ increment operator here:


counter = counter + 1;



Like this:

++counter;




There is a += operator you can use here:


counter = counter + 2;



Like this:

counter += 2;




There is a Math.Pow() method you can use:


temp2 = temp * temp;



Like this:

temp2 = Math.Pow(temp, 2);