Ben Ziegler
Ben Ziegler

Reputation: 973

linq to sql syntax different but should get the same results

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?

Upvotes: 2

Views: 203

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499800

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.

Upvotes: 7

Daniel A. White
Daniel A. White

Reputation: 190907

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

Upvotes: 7

Related Questions