Tech Off Thread

7 posts

Linq and where clauses

Back to Forum: Tech Off
  • User profile image
    PerfectPhase

    So I was watching some of the PDC talks and noticed that some people write where clauses like this..

    var result = from item in source 
                  where item.Name == "John"
                  where item.Country == "UK"
                  select item

    rather than like this

    var result = from item in source 
                  where item.Name == "John" && item.Country == "UK"
                  select item

    And I was wondering why and if there is a difference in the final expression tree produced.

    Cheers,

    Stephen.

     

  • User profile image
    androidi

    Not sure if this is what you asked and I didn't try Linq to SQL but atleast the IL produced is identical (inside Linqpad). I couldn't figure how to get an expression tree out of that into the expression tree visualizer that's in the VS 2008 C# samples. (I haven't really studied expression trees at all so hopefully you get better answer)

  • User profile image
    spivonious

    @PerfectPhase: Weird. I wouldn't have thought the first one would even compile. And just so you know, the "select item" part isn't needed.

  • User profile image
    Ajain

    Just for your information first one is more expensive than the second one as per performance wise. Becuase the second one translate into one function<TSource,Bool> while the first one transfer into three function.

  • User profile image
    PerfectPhase

    @Ajain: Ah thought that might be the case.  I would have lingered on it, but it was Bart de Smet, and he really knows his linq Smiley

     

  • User profile image
    joechung

    , spivonious wrote

    @PerfectPhase: And just so you know, the "select item" part isn't needed.

    That isn't correct.  I get a "query body must end with a select clause or a group clause" error without it.

  • User profile image
    spivonious

    , joechung wrote

    *snip*

    That isn't correct.  I get a "query body must end with a select clause or a group clause" error without it.

    Hmm, it appears to be invalid in C#. It works in VB. Yet another one of the mysteries of life. Smiley

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.