Geeks With Blogs
Blog Moved to http://podwysocki.codebetter.com/ Blog Moved to http://podwysocki.codebetter.com/
In the first look I posted last week, I asked the question why the var keyword for implicit types were so powerful and more than just syntactic sugar.  After a response, I then realized I overlooked something pretty obvious with regards to LINQ queries. 
 
I found this post from Cyrus' Blather to be quite helpful:  http://blogs.msdn.com/cyrusn/archive/2005/09/13/465390.aspx
 
Let's just go over the details for my own piece of mind.  Let's compare how we would do each query in .NET 1.1, 2.0 and now 3.0.
 
First, let's do a simple example in 1.1 by finding customers in Washington:
 
Customer[] customers = GetCustomers();
ArrayList custInWashington = new ArrayList();
foreach(Customer customer in customers)
{
     if(customer.City == "Washington")
          custInWashington.Add(customer);
} // foreach - customer
 
As you can see, there is quite a bit of code involved in just narrowing down to customers in Washington in 1.1.  Now, let's take a look at 2.0 syntax using Generics to solve our little problem:
 
List<Customer> customers = GetCustomers();
List<Customer> custInDC = customers.FindAll(delegate(Customer cust) { return cust.City == "Washington"; });
 
Now as we note from the above example, we used an anonymous method to define the delegate handler to determine whether the City is Washington.  It can get a little clumsy and it'd be nice if we could clean up the code just a little bit.  Below, I will do the last piece in C# 3.0 to clean up our code with a query:
 
Customers[] customers = GetCustomers();
var custInDC = customers.Where(c=>City == "Washington);
 
The above statement creates the custInDC to an IEnumerable<Customer> implicitly which is very nice.  As you can see, I'm barely scratching the surface, but I'm definitely looking forward to looking more into C# 3.0.
 
 
Posted on Monday, May 15, 2006 12:06 PM .NET , C# | Back to top


Comments on this post: C# 3.0 - First look at LINQ and implicit types

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Matthew Podwysocki | Powered by: GeeksWithBlogs.net