29 April 2008 5:47 PM

Why .NET IEnumerable predicates are cool

Instead of having to do this:

int totalBlack = 0;
int totalGray = 0;
int totalOrange 0;

List cats = this.GetAllCats();

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 cats = this.GetAllCats();
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:

At May 1, 2008 9:07 AM , Blogger Paul Kinlan said...

Is this not a less efficient way of doing the counts? You are essentially looping through the data 2 extra times.

 
At May 2, 2008 10:28 AM , Blogger Straylight said...

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