views:

49

answers:

2

I was playing around with expression trees and various Linq syntax. I wrote the following:

using (NorthwindDataContext DB = new NorthwindDataContext())
        {
            DataLoadOptions dlo = new DataLoadOptions();

            // Version 1
            dlo.AssociateWith<Customer>(c => c.Orders.Where(o => o.OrderID < 10700).Select(o => o)); 

            // Version 2
            dlo.AssociateWith<Customer>(c => from o in c.Orders
                                             where o.OrderID < 10700
                                             select o);
        }

The Version 1 method returns an error saying "The operator 'Select' is not supported in Subquery."

While Version 2 runs just fine. From what I understand I am writing the exact same thing, but one is with the "dot" notation syntax and the other is query expression syntax.

Am I missing something here? Why the error on one but not the other "if" they are in fact the same query?

+7  A: 

You don't need the .Select(o => o) in your query.

Daniel A. White
+7  A: 

To expand on Daniel's answer, the select o is known as a degenerate query expression - and it's removed by the C# compiler. So your query is translated to:

c.Orders.Where(o => o.OrderID < 10700)

Note that without the where clause, however, the compiler would still include the Select call, so:

from o in c.Orders
select o

is translated to

c.Orders.Select(o => o)

From section 7.15.2.3 of the language spec:

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.

Jon Skeet
Thanks to both answers and the great explanation Jon.
Ben Ziegler