Why .NET IEnumerable predicates are cool
Instead of having to do this:
int totalBlack = 0;
int totalGray = 0;
int totalOrange 0;
List
foreach (Cat cat in cats)
{
if (cat.Color == Color.Black)
totalBlack++;
else if (cat.Color == Color.Gray)
totalGray++;
else if (cat.Color == Color.Orange)
totalOrange++;
}
All I have to do is this:
List
int totalBlack = cats.Count(cat => cat.Color == Color.Black);
int totalGray = cats.Count(cat => cat.Color == Color.Gray);
int totalOrange cats.Count(cat => cat.Color == Color.Orange);
And that's just the Count() method. I haven't even tried the others like Union(), Where(), Min(), etc.
In the immortal words of Cartman...Sweet
2 Comments:
Is this not a less efficient way of doing the counts? You are essentially looping through the data 2 extra times.
Paul - you're quite right, I hadn't thought of that.
For a large collection this would be inefficient, for smaller ones I think it would be fine.
Post a Comment
Links to this post:
Create a Link
<< Home