HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Exclude scores when flag is set

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
flagexcludescoreswhenset

Problem

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 && studentScore == 0)
    { 
        continue; 
    }
    else 
    { 
        count++; 
    }
}

Solution

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 => GetScore(student));
int count = scores.Count(score => !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=>x);
var bottomTen = sorted.Take(10);


and so on.

Code Snippets

var scores = students.Select(student => GetScore(student));
int count = scores.Count(score => !excludeZeros || score != 0);
int total = scores.Sum();
var scores = from student in students
             let score = GetScore(student)
             where !excludeZeros || score != 0
             select score;
int count = scores.Count();
int total = scores.Sum();
int maximum = scores.Max();
int average = scores.Average();
var sorted = scores.OrderBy(x=>x);
var bottomTen = sorted.Take(10);

Context

StackExchange Code Review Q#129175, answer score: 19

Revisions (0)

No revisions yet.