Where does the LINQ query syntax come from?

I'm new to C# and have just started to delve into using classes that essentially mirror a database. What I'm confused about is how I'm able to use lines like

var queryLondonCustomers = from cust in customers
                           where cust.City == "London" 
                           select cust;

in my program. From what I understand, that syntax isn't "normal" C#, so the above line wouldn't have any meaning if I hadn't included System.Linq. What is happening is we've added to the C# sharp language in the context of this file.

Maybe I'm completely wrong. Could someone clear this up for me? I come from a C++ background, so maybe I'd understand if someone could show me the C++ equivalent of this concept.

And if I'm right, why is this way of doing things preferable to having a C# class that talks to the database by using strings that are database queries, like with PHP and MySQL? I thought this MVC way of talking to the database was supposed to provide an abstraction for me to use a C# class for database operations, but really this is just taking database language and adding it to the C# language in the context of a particular C# file. I can't see any point of that. I'm not trolling, just trying to understand the spirit of this whole ASP.NET MVC thing that is the most confusing thing I've learned so far.

Jon Skeet
people
quotationmark

From what I understand, that syntax isn't "normal" C#

Yes it is, as of C# 3.

so the above line wouldn't have any meaning if I hadn't included System.Linq

Yes it would. It would still have effectively been transformed by the compiler into:

var queryLondonCustomers = customers.Where(cust => cust.City == "London");

(The lack of a Select call is because you're selecting the range variable directly, rather than some projection of it.)

If that code would have compiled (e.g. because of a Where member in customers, or due to another extension method on its type) then so would the query expression.

Query expressions are specified in section 7.16 of the C# language specification.

As for the question of why you'd want to do this, well:

  • Using an ORM instead of just manual SQL is hardly new - but LINQ integrates it into the language, with a somewhat leaky abstraction
  • LINQ doesn't just work for databases; I primarily use it in "regular" collections such as lists etc.

people

See more on this question at Stackoverflow