views:

50

answers:

1

Using the query expression style, the let clause can be easily written. My question is how to use the dot notation style to write a let clause.

+2  A: 

Essentially it's a Select (in most cases) which introduces a transparent identifier - via an anonymous type which encapsulates all the currently specified range variables. For example, this query:

string[] names = { "Jon", "Mark" };

var query = from name in names
            let length = name.Length
            where length > 3
            select name + ": " + length;

is translated into something like this:

var query = names.Select(name => new { name, length = name.Length })
                 .Where(z => z.length > 3)
                 .Select(z => z.name + ": " z.length);
Jon Skeet
Don't mean to criticize your answer (on contrary I appreciate it), but since I could use the let clause to write much more complicated method and in your example here, the dot notation is already longer and less readable than the query exp counterpart, I take that this is another case where query exp is more preferable than the dot nation. The other case that I know involves writing joins. Would you agree with that observation? Thanks for your answer.
Khnle
@Khnle: It's probably a matter of personal preference. I actually prefer the look of the dot notation in this case. Once you get used to the lambda syntax, it's quite easy to read, more descriptive of what is actually happening under the hood, and doesn't require the additional syntactic sugar of the `let` statement.
Robert Harvey
@Khnle: Yes - I generally find that query expressions which introduce transparent identifiers (including let and join) are more readable than their dot notation equivalents. Robert's right though - it's definitely a personal preference.
Jon Skeet