Select method is not called using LinQ query syntax

前端 未结 3 1820
一个人的身影
一个人的身影 2021-01-20 01:53

I want to enable LinQ query syntax over my classes. I think query syntax is translated to method syntax, for example:

var query = from p in new Class1

        
3条回答
  •  悲&欢浪女
    2021-01-20 02:20

    Someone knows why?

    Yes, because that's what the language specification says to do. The query expression translation is all in section 7.16.2 of the C# 5 specification.

    Section 7.16.2.5 explains why your initial example is incorrect - Select won't be called:

    A query expression of the form

    from x in e select v
    

    is translated into

    ( e ) . Select ( x => v )
    

    except when v is the identifier x, the translation is simply

    ( e )
    

    For example

    from c in customers.Where(c => c.City == “London”)
    select c
    

    is simply translated into

    customers.Where(c => c.City == “London”)
    

    However, that isn't the case for degenerate query expressions which are covered in 7.16.2.3 - which explains what happens when you remove your where clause:

    A query expression of the form

    from x in e select x
    

    is translated into

    ( e ) . Select ( x => x )
    

    The example

    from c in customers
    select c
    

    Is translated into

    customers.Select(c => c)
    

    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.

提交回复
热议问题