Friday, September 16, 2005

Language Integrated Query

Microsoft has come up with something called Language Integrated Query (LINQ) in C#3.0 (actually it is supported in CLR, so in also). This is too cool. What this means is that you will be able to write SQL kind of queries directly in the language. How this differs, well take an example in java where i try to query something

PreparedStatement pstmt = con.prepareStatement("select name from Employee");

Now the query is just a string. It doesnt have any compile time checking, say if you write mame instead of name, you will need to wait until runtime to find that error. (Not that this makes a big difference, because you should always write unit tests to verify your program parts).
Lets see how this is with C#3.0

Customers[] customers = ...

var q = from c in customers
where c.City == "London"
select new {c.CompanyName, c.Phone};

Now lets look at this in detail.

First, we see that whatever query we are writing is working on customer array. So the LINQ not only works with database, but with in memory collection, xml etc. So it is in fact "integrated" with language(C#), database, xml.

Second, we see that from comes before select unlike in SQL. (in sql you write
select foo from bar
from bar select foo
). Why this is so? well if you think about it the bar scope should actually come before foo. ie foo is a field in bar. so if you dont specify bar before foo, how the can say editor know about foo.

ie say you are writing in the ide

from bar select .. 
(and press ctrl + space)
you get all the fields in bar, because we specified bar before select.

if it was the other way around

select .. 
(press ctrl + space)
nobody has any idea on what object you are writing query .. (bar is still in your head)

So in C# they made from before select. You get intellisense in your query!

Third, we see something
new {c.CompanyName, c.Phone}
. what is this? well this is a new object which has fields CompanyName & Phone. You dont have to create a new class for it, it is anonymous.and the type of q is if you say q. (ctrl + space), only CompanyName and Phone pops up. Well there are many more type inferencing going on with anonymous functions (lambda) etc .. all with compile time type checking. (well even though i love python with dynamic typing, intellisense is one thing which is the way to go).

I dont know how many lines of code are going to be reduced because of these new features.

From Anders Hejlsbergs video, i see a lot of things .. please do check it from here

Java is trailing behind C# .. they have good Generics support with reification, .. now this LINQ. All are looking so cool. It will be interesting to see how java catches up.
Talking about microsoft, there are tons of stuff they are coming up with ie7, sparkle... in this year's PDC .. see them at channel9

Update: covered in slashdot

No comments: