Daniel Hoelbling-Inzko talks about programming

Don’t get spoiled by LinQ To SQL

Posted by Daniel Hölbling on December 16, 2008

I got introduced to LinQ through the famous posts by ScottGu on Linq-to-Sql and always thought of LinQ as some really cool language thing that automagically enabled me to write queries within .NET.

All of ScottGu’s samples look like actual SQL Queries with real keywords within the language like:

var result =   from s in strings
               where s.StartsWith("d")
               select s;

So, when I was just briefly trying to get stuff done I used all those keywords as they seemed to fit and didn’t really try to understand the “deeper” concept behind those (as they magically generated SQL queries). MS introduced new keywords into the language, so be it, I was looking them up in MSDN and used them as such when using the LinQ-to-Sql datacontext.

Now, that I (and apparently Microsoft) have departed from LinQ-to-Sql I somehow forgot about LinQ for quite some time simply because I had no need for in-memory-queries for quite some time. And to be honest, I also never really thought about applying that strange LinQ syntax to objects in memory (I considered the above mentioned LinQ query more as a “c# strongly typed version of SQL” rather than a in-memory query method)

So, I was quite amazed of what you can actually do with LinQ if you abandon this strange undiscoverable SQL syntax and simply use method chaining. The above query can be rewritten without any “keyword magic” but with plain objects to look like this:

var result = strings.Where(s => s.StartsWith("d"));

The beauty of it? All the LinQ overloads reside on the IEnumerable<T> interface, and most of these methods will return an IEnumerable<T> so you can “chain” those method calls together like this:

var result = strings
            .Where(s => s.StartsWith("d"))
            .OrderBy(p => p.Length)
            .Select(p => p.Substring(0, 4));

And now the whole thing started to make sense. I can easily grasp how this is supposed to work, instead of looking at awe at the “SQL query” that magically works. And that’s where I went wrong the first time.

Instead of learning LinQ to objects first, I got caught in the database centric world of LinQ-to-Sql that made me not think of LinQ as anything other than a Database query tool.

Filed under net, programmierung
comments powered by Disqus

My Photography business


dynamic css for .NET