Monday, January 07, 2008

Count things with Linq

I had a situation where I needed to determine how many objects in a generic list were missing a value in a property.  That count was very important to the user.  Basically, I was looking for all the objects in the list that didn't have a value in the path property.  Normally, I would have created a count integer and a loop of some sort and just counted. 

int count = 0;
foreach(Profile p in Profiles)

I could have also used an anonymous delegate, but I was playing with Linq and found this little short cut.

int count = (from p in profiles where String.IsNullOrEmpty(p.Path) select p).Count();

I think that this is much cleaner and easier to read.   Happy Linq'n!

No comments: