Cool LINQ stuff

LINQ is so cool. There’s just so much related to it that I feel like I don’t even know where dig deeper into it.

Coming from a Visual FoxPro background, I got pretty used to having a query language integrated right into the language. I also got pretty used to OOP, since VFP has OOP support since 1995. When I first got into .NET and noticed there wasn’t anything like VFP’s built-in query language, I thought "hmmm… this thing sucks!".

I was used to querying a backend to retrieve some data, and then query the in-memory data to do some filtering, sorting, etc, on the client side; all that was possible in VFP, but couldn’t really do it in .NET. The DataTable class has methods such as Select (that takes a "where-like" clause and returns an array of DataRows that match the criteria), and the Rows collection has a Find method (that takes a primay key and returns a reference to the row that matches the criteria). One can also play with DataViews to do some filtering and sorting (which I must confess I do like since it gives different views over the same set of data). But still, that all sucked when compared to doing a SELECT FieldA, FieldB FROM SomeInMemoryData WHERE Whatever = true GROUP BY Something ORDER BY SomethingElse right into the source code.

Enters LINQ!

One of the limitations of SQL as we know it in, say VFP or T-SQL, is that we query from rectangular data, and the outcome is another set of rectangular data. One cannot really create a result that’s a different "type":

RectToRect

One of the cool things about LINQ is that a query can go against any source that implements IEnumerable<T>, and the outcome can be really anything! For instance, one could query a collection of business entities, and the outcome could be a list of edit forms bound to the entities gathered by the query.

In other words, say my edit Form takes in an entity in its constructor, and uses that entity to bind it to UI controls… something simple like this:

    public partial class CustomerEditForm : Form
    {
        public CustomerEditForm(CustomerBusinessEntity entity)
        {
            InitializeComponent();

            this.textBox2.Text = entity.Name;
        }
    }

 Now say we have a collection of CustomerBusinessEntities like so:

var customers = new List<CustomerBusinessEntity>{
                new CustomerBusinessEntity("Claudio Lassala"),
                new CustomerBusinessEntity("John Jones"),
                new CustomerBusinessEntity("Cartman Smith")};

Say we want to write a query against that collection, looking for all Customers whose name starts with "C", and the outcome should be a collection of edit forms loaded with the entities gathered by the query. This is the code that does just that:

            var customerForms = 
                from customer in customers
                where customer.Name.StartsWith("C")
                select new CustomerEditForm(customer);

Now we can iterate through the query results and show the forms:

            foreach (var form in customerForms)
            {
                form.Show();
            }

 …and get the following result:

linqforms[1][1]

I think that is REALLY cool!

This sample uses the flavor of LINQ known as LINQ to Objects. There are other flavors of LINQ, such as LINQ to SQL (queries against SQL Server), LINQ to XML (queries against XML documents), etc. Those different flavors can be mixed, making it possible to implement some very interesting scenarios.

For instance, a query could select customers from a SQL database, join data from customers’  RSS feeds, join data from customers’  emails coming from Exchange server, do all sorts of filtering, grouping, sorting, etc., and the outcome could be, for instance, an XML document formatted to be consumed by some service that expects that format.

There’s a lot of great content regarding LINQ to SQL and LINQ to XML out there. For LINQ to SQL, make sure to check out Rick Strahl’s blog; he’s got a lot of great posts related to the topic, including some great stuff on how to create a business framework around LINQ to SQL to hide some of the plumbing from the developer. Also check out Scott Guthrie’s blog; he’s also got a lot of great tutorials on LINQ to SQL.

For LINQ to XML, check both Scott Hanselman’s blog (he’s got a bunch of posts about it), as well as this DNRTV episodes with DonXML.

There’s actually a lot of talk about LINQ to SQL and LINQ to XML, but I don’t hear a lot of talk about LINQ to Objects, and it seems to me the reason for that is because a lot of people haven’t quite figured out about this. I’ll continue posting what I considered cool queries that can be created with LINQ to Objects.

Advertisements

  1. Leave a comment

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: