Two ways to use a predicate in LINQ to Filter Results

I've been using a lot of LINQ lately at my current client and I'm really starting to appreciate the power of thinking this way, simply because it greatly reduces my code footprint and concisely illustrates what I'm trying to do in my collections in a single line of code.

One of the powerful features of LINQ is the ability to filter a collection for the desired results.  Lets take the situation where we have a list of customers in memory and we want to count how many customers share a zipcode of  81045.

Here is our list of customers in a static array in memory. Note that only 2 customers share this zip code


static
IEnumerable<Customer> Customers = new List<Customer>()
{
new Customer(){Name="Fred", Zip="78705"},
new Customer(){Name="Mahesh", Zip="01003"},
new Customer(){Name="Mike", Zip="20450"},
new Customer(){Name="Nina", Zip="81045"},
new Customer(){Name="Bill", Zip="81045"}};

In the old way of doing things, we could simply loop through the list of customers, look for the zip code of 81045, and everytime we saw this value, increment a counter:

int count = 0;
foreach (var customer in Customers)
{
   if (customer.Zip == "81045")
      {
          count++;
      }
}

In Linq, we think more like a database analyst.  What are we filtering on?  We want to count all customers in the customer list who have a zipcode of 81045.  So in essense, we want to reduce the list down to the customers with zipcode 81045 and count them.

In linq this is accomplished with Where which is the filter and Count which counts the number of items returned by the filter.  The filter is simply a check to see which zip codes equal 81045.



var count = Customers.Where(c => c.Zip == "81045").Count();

In .NET 3.5  you can accomplish the filtering in an even briefer coding statement (if you can believe that!).  You can simply put the filter directly in the Count method, therefore eliminating the need for a Where call.


var
count = Customers.Count(c => c.Zip == "81045");

The LINQ really brings our logic down to a simple and precise statement and IMHO greatly improves the code.