score:3

Accepted answer

in your second example, the call to select is not redundant. if you would omit the select call, the query would just return the original collection, whereas select returns an ienumerable.

in your first example, where already returns an ienumerable and the select clause doesn't do any work, so it is omitted.

score:1

because in the query version there is no actual select projecting 'c' into something else, it is just passing on 'c' as-is. which results in only a call to 'where'.

in the second variation, you explicitly call 'select' and thus do a projection. yes, you are only returning the same objects, but the compiler will not see this.

score:5

the c# compiler is clever and remove useless statement from linq. select c is useless so the compiler remove it. when you write select(c=>c) the compiler can't say that's the instruction is useless because it' a function call and so it doesn't remove it. if you remove it yourself il become the same.

edit : linq is a "descriptive" language : you say what you want and the compiler transforms it well. you don't have any control on that transformation. the compiler try to optimize function call and don't use select because you don't do projection so it's useless. when you write select(c => c) you call a function explicitely so the compiler won't remove it.

var a = from c in companies select c;
var a = c.select(elt=>elt);

select is usefull in this example. if you remove it a has the type of c; otherwise a is an ienumerable

score:5

@mexianto is of course correct that this is a compiler optimization.

note that this is explicitly called out in the language specification under "degenerate query expressions." also note that the compiler is smart enough to not perform the optimization when doing so would return the original source object (the user might want to use a degenerate query to make it difficult for the client to mutate the source object, assuming that it is mutable).

7.16.2.3 degenerate query expressions

a query expression of the form

from x in e select x

is translated into

( e ) . select ( x => x ) 

[...] a degenerate query expression is one that trivially selects the elements of the source. a later phase of the translation removes degenerate queries introduced by other translation steps by replacing them with their source. it is important however to ensure that the result of a query expression is never the source object itself, as that would reveal the type and identity of the source to the client of the query. therefore this step protects degenerate queries written directly in source code by explicitly calling select on the source. it is then up to the implementers of select and other query operators to ensure that these methods never return the source object itself.


Related Query

More Query from same tag