Exclude scores when flag is set I am not sure if I am just having a brain lapse here or if there is a better way to do this:

I am trying to only add one to count in the following scenarios:


the bool excludezeros is set to false (count should be increased for iterations of the foreach)
the bool excludezeros is set to true and studentScore is not equal to 0 (count only increases when student score is not equal to 0)


Here is what I have:

foreach (var student in students)
{
    double studentScore = GetScore();
    score += studentScore;
    if (excludeZeroes &amp;&amp; studentScore == 0)
    { 
        continue; 
    }
    else 
    { 
        count++; 
    }
}
I agree with forsvarir's answer, that you should lose the continue by inverting the condition.  But you can do one better than that: lose the loop!

var scores = students.Select(student =&gt; GetScore(student));
int count = scores.Count(score =&gt; !excludeZeros || score != 0);
int total = scores.Sum();


Done. No loop needed. 

Or equivalently:

var scores = from student in students
             let score = GetScore(student)
             where !excludeZeros || score != 0
             select score;
int count = scores.Count();
int total = scores.Sum();


You know what is really nice about doing it this way? First, the code looks like what it means; it's closer to the "business domain" of the code. Second, it is super easy to extract more statistics:

int maximum = scores.Max();
int average = scores.Average();
var sorted = scores.OrderBy(x=&gt;x);
var bottomTen = sorted.Take(10);


and so on.