Why is this LINQ query compiling?

After reading Jon Skeet's Odd Query Expressions , I tried the code below. I expected the LINQ query at the end to translate to int query = proxy.Where(x => x).Select(x => x);, which does not compile because it Wherereturns int. The code is compiled and prints "Where (x => x)" on the screen, and the request is on 2. Select is never called, but it should be where the code is to be compiled. What's happening?

using System;
using System.Linq.Expressions;

public class LinqProxy
{
    public Func<Expression<Func<string,string>>,int> Select { get; set; }
    public Func<Expression<Func<string,string>>,int> Where { get; set; }
}

class Test
{
    static void Main()
    {
        LinqProxy proxy = new LinqProxy();

        proxy.Select = exp => 
        { 
            Console.WriteLine("Select({0})", exp);
            return 1;
        };
        proxy.Where = exp => 
        { 
            Console.WriteLine("Where({0})", exp);
            return 2;
        };

        int query = from x in proxy
                    where x
                    select x;
    }
}
+5
source share
2 answers

, "select x" no-op - Select(x => x) . where. . . 7.16.2.3 # 4. :

- , . , , . , , . , , Select . Select , .

, ( )

// Query                          // Translation
from x in proxy                   proxy.Where(x => x)
where x
select x


from x in proxy                   proxy.Select(x => x)
select x               


from x in proxy                   proxy.Where(x => x)
where x                                .Select(x => x * 2)
select x * 2
+11

, LINQ .

int query = from x in proxy
            where x
            select x;

int query = proxy.Where(x => x);     // note it optimises the select away

, Where Select proxy. , , , Select .

- :

    int query = from x in proxy
                select x.ToString();

:

int query = proxy.Select(x => x.ToString());

Select.

+7

All Articles