patterncsharpModerate
Exclude scores when flag is set
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
Here is what I have:
I am trying to only add one to
count in the following scenarios:- the bool
excludezerosis set tofalse(count should be increased for iterations of theforeach)
- the bool
excludezerosis set totrueandstudentScoreis 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!
Done. No loop needed.
Or equivalently:
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:
and so on.
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.