Changed selection order due to space in LINQ? What is the reason?

What is the reason for changing the order of these Microsoft operators? Microsoft does not use select-from-where and changes this order to from-where-select . What for? Is this just for the best intellisense in VS?

+4
source share
3 answers

As mentioned above, this makes IntelliSense possible, and it makes the request read in the same order that the operations are actually performed: first you get the collection, then you filter it, then you design the filtered results.

The third reason is that this order makes the rules for determining the scope more efficient. You will notice that in C # you never enter a new area that "flows to the left." In SQL, material that is entered into a region by FROM is used to the left of FROM. In C # syntax, range variables must be used explicitly, so they need to be declared to the left of the code that uses them; range variables are then in scope in different parts of the query.

One weird thing about coverage rules is the connection proposal. When you say

 from c in customers join o in orders on c.Id equals o.CustomerId 

...

the range variable c is in scope between on and equals , but o is not. The scope still moves to the right, but in some cases it may skip the sub here and there.

+8
source

This not only improves Intellisense, but also reflects the actual order of operations. For example, from e in Employees where e.Age > 65 select e.Salary will be rewritten as Employees.Where(e => e.Age > 65).Select(e => e.Salary) .

It would not make sense to write Select(e => e.Salary).Employees.Where(e => e.Age > 65) .

+7
source

LINQ is intended not only for database related operations, but also for general querying and designing data in memory. Also consider lambda expressions and extension methods, which LINQ query expression syntax is syntactic sugar for.

 var query = from foo in foos where foo.Bar == "Blah" select foo.Id; 

Is syntactic sugar for

 var query = foos.Where(foo => foo.Bar == "Blah").Select(foo => foo.Id); 

The syntax of the existing query syntax is close to the lambda / extension syntax, and one of the first things the compiler does is translate the former into the latter anyway. This more clearly describes the order of things that actually happen.

+6
source

Source: https://habr.com/ru/post/1306002/


All Articles