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.

Mike GoldPosted Jan 31, 2010, 5:37 PM
I agree Mahesh, There will be a learning curve for existing .NET developers, not only because of the strange syntax, but because it leapfrogs C# into the land of Functional Programming, which some may note is not really object-oriented programming. But the more I use the functional programming tools in .NET the more I like how clean they make the code look once you get accustomed and comfortable with the lambda syntax.
Mahesh ChandPosted Jan 31, 2010, 9:49 AM
Mike I agree Mike. Not only LINQ gives us the power and make code simpler but also is very fast since collection is already in memory. So we do not need to make database trips. One thing I notice developers do not like LINQ yet is complex syntax. It will take a while to get used to the syntax.