Sneak peak at Linq from C# 3.0 perspective

You might be wondering where all this C# 3.0 is going. Especially when reading the previous post on Lambda expressions. Let me give you a sneak preview of how Linq needs most of what’s in C# 3.0.


Linq uses lambda expressions quite heavily. Linq expresses queries with query operators, which essentially are methods that work on IEnumerable<T> implementing types (well, sort of. This is half the truth. Read slidedeck as pdf here.) So, given an array or collection (which implements IEnumerable<T>), there is a query operator Where that filters out values based on a predicate (read: filter) function that we must pass. In psuedo-code this is:  IEnumerable<Customer> filteredCustomers = customers.Where(delegate object to predicate function)


Instead of defining a formal function or a clumsy anonymous method:



IEnumerable<Customer> = customers.Where(delegate (Customer c) { return c.Country == “The Netherlands”; });


we can write this much more elegantly with a lambda expression:



IEnumerable<Customer> = customers.Where(c => c.Country == “The Netherlands”);


Without Lambda expressions such operators would be harder to read and more difficult to understand. When you take a look at how the Where operator is defined in System.Core.dll, you will see that an extension method declared in System.Query.Sequence does the job.



public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate)


Notice the use of Func<T, bool> for the delegate type to the predicate function. Obviously a “where” filters out values based on a boolean evaluation.


Makes sense?

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s