<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;D08HSHc9eSp7ImA9WhRaF0o.&quot;"><id>tag:blogger.com,1999:blog-3761236184475964431</id><updated>2012-02-20T23:10:39.961+01:00</updated><category term="C#" /><category term="linq" /><category term="expression" /><category term="parser" /><category term="lambda" /><category term="foreach" /><title>KrizzCode</title><subtitle type="html">Welcome to the blog of Krzysztof Olczyk - software engineer interested in various technologies.  You will find here, posts regarding topics connected more or less tightly with developing applications. It would be based on what I am currently doing, what I have discovered, what I have created, etc. 
Enjoy!</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.krizzcode.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://www.krizzcode.com/" /><author><name>Krzysztof Olczyk</name><uri>http://www.blogger.com/profile/02591842280854638602</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="29" src="http://4.bp.blogspot.com/-mjmhn4Rowck/TzWptG98mbI/AAAAAAAATQE/SgsPb-HGwAw/s220/me_degustation.png" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>2</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/KrizzsCode" /><feedburner:info uri="krizzscode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;CUcCRn0-eCp7ImA9WhRUGUg.&quot;"><id>tag:blogger.com,1999:blog-3761236184475964431.post-494878170161438692</id><published>2012-01-24T10:11:00.003+01:00</published><updated>2012-01-30T20:51:07.350+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-30T20:51:07.350+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="parser" /><category scheme="http://www.blogger.com/atom/ns#" term="expression" /><category scheme="http://www.blogger.com/atom/ns#" term="linq" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Extending DynamicLINQ language: Specifying class name in "new" clause</title><content type="html">Dynamic Linq &lt;a href="#adn1"&gt;(1)&lt;/a&gt; is a library provided in source code by Microsoft which provides dynamic linq capabilities - i.e. you can construct queries as strings instead of type-safe programming language constructs as in the default linq. The library provides additional extension methods for &lt;b&gt;IQueryable&lt;t&gt;&lt;/b&gt; like &lt;b&gt;Where&lt;/b&gt; and &lt;b&gt;Select&lt;/b&gt; which accept strings which represent queries which are parsed in the runtime into the adequate lambda expressions for linq expression tree. 
&lt;br/&gt;&lt;br/&gt;
It allows you to write queries like the following:
&lt;pre class="brush: csharp"&gt;var query = YourDB.Products.Where("CategoryID = 2 And Price &lt; 10").OrderBy("StockCount");
&lt;/pre&gt;

What can constitute the string is a simple specific &lt;i&gt;DynamicLinq language&lt;/i&gt; which is well documented in the documents attached to the DynamicLinq package. The heart of DynamicLinq is actually an implementation of a parser for this microlanguage which parses the given string into &lt;b&gt;Expression&lt;/b&gt; object.
&lt;br/&gt;&lt;br/&gt;
The part of the language is an ability to instantiate new objects of anonymous classes, especially useful in &lt;b&gt;Select&lt;/b&gt; and &lt;b&gt;SelectMany&lt;/b&gt; directives.
You can do e.g.:

&lt;pre class="brush: csharp"&gt;cars.Select("new (name, year, engine.type as engine_type)");
&lt;/pre&gt;

This will construct the object containing properties: &lt;b&gt;name&lt;/b&gt;, &lt;b&gt;year&lt;/b&gt; and &lt;b&gt;engine_type&lt;/b&gt;.
&lt;br/&gt;&lt;br/&gt;
In standard Linq as in e.g. C#, apart from dynamic "typeless" objects, you are able to construct the query in such a way that the objects of already existing type are returned. This is, however, not possible with the DynamicLinq as provided by Microsoft.
&lt;br/&gt;
Nevertheless, with some knowledge of how compilers (or more precisely parsers) work, some understanding of lambda expression trees in .NET and after analyzing the source code of &lt;b&gt;Dynamic.cs&lt;/b&gt; (file containing the implementation of the DLinq), 
it is relatively easy to extend it with the capabilities to name the existing types to be created in &lt;b&gt;new&lt;/b&gt; clauses. 
&lt;br/&gt;&lt;br/&gt;
Currently, the grammar for &lt;b&gt;new&lt;/b&gt; expression in DynamicLinq language is as following: 
&lt;pre class="brush: csharp"&gt;
new (expr1 as name1, expr2 as name2, ..., exprn as namen)
&lt;/pre&gt;

where &lt;b&gt;name#&lt;/b&gt; is the name of the property in the resultant object which will hold the value evaluated from &lt;b&gt;expr#&lt;/b&gt;. If the expression boils down to the property getter, the &lt;i&gt;as name#&lt;/i&gt; part can be omitted and the property in the resultant object will be exact to the name of evaluated property. 

We can extend the grammar in the following manner without introducing ambiguity:
&lt;pre class="brush: csharp"&gt;
new Namespace.TypeName (expr1 as name1, expr2 as name2, ..., exprn as namen)
&lt;/pre&gt;

Not providing the &lt;b&gt;TypeName&lt;/b&gt; will still denote the instantiation of an anonymous object.  

If we take a look at &lt;b&gt;ExpressionParser&lt;/b&gt; class, we quickly localize the method &lt;b&gt;ParseNew&lt;/b&gt;. This is, indeed, a method responsible for parsing the &lt;b&gt;new&lt;/b&gt; expression.

Currently, the parse method looks more or less like the following:
&lt;ol&gt;
  &lt;li&gt; Consume "new" keyword. &lt;/li&gt;
  &lt;li&gt; Consume opening parenthesis &lt;/li&gt;
  &lt;li&gt; Loop doing the following:
    &lt;ol type="a"&gt;
       &lt;li&gt; Parse expression &lt;/li&gt;
       &lt;li&gt; If next token is "as" consume it and the following token as an identifier &lt;/li&gt;
       &lt;li&gt; Store the dynamic property definition using the obtained name and expression &lt;/li&gt;
       &lt;li&gt; If the next token is comma, consume and continue; otherwise break loop.
    &lt;/ol&gt; &lt;/li&gt;
   &lt;li&gt; Consume closing parenthesis &lt;/li&gt;
   &lt;li&gt; Synthesize and instantiate the anonymous type based on the accumulated dynamic property definitions.
   &lt;li&gt; Return the expression tree node for type instantiation parametrized by the obtained type.
&lt;/ol&gt; 

In order to support our new grammar, we will have to add more steps between &lt;b&gt;1&lt;/b&gt; and &lt;b&gt;2&lt;/b&gt; which before consuming the opening parenthesis will consume as many as possible identifiers separated by &lt;b&gt;dot&lt;/b&gt;(.) which will constitute the name for the existing type. Additionally, if any such identifier is actually present, we will toggle the flag signalizing that we are constructing the object of the existing type. &lt;br/&gt;
With the flag on, instead of points &lt;b&gt;5&lt;/b&gt; and &lt;b&gt;6&lt;/b&gt;, we will instantiate the existing type using &lt;b&gt;Type.GetType&lt;/b&gt; and bind the expressions values to its already present properties. 
&lt;br/&gt;&lt;br/&gt;
Finally, the &lt;b&gt;ParseNew&lt;/b&gt; method will look like the following:
&lt;pre class="brush: csharp"&gt;
Expression ParseNew() {
    NextToken();

    bool anonymous = true;
    Type class_type = null;

    if (token.id == TokenId.Identifier)
    {
        anonymous = false;
        StringBuilder full_type_name = new StringBuilder(GetIdentifier());
        
        NextToken();
        
        while (token.id == TokenId.Dot)
        {
            NextToken();
            ValidateToken(TokenId.Identifier, Res.IdentifierExpected);
            full_type_name.Append(".");
            full_type_name.Append(GetIdentifier());
            NextToken();
        }
        
        class_type = Type.GetType(full_type_name.ToString(), false);    
        if (class_type == null)
            throw ParseError(Res.TypeNotFound, full_type_name.ToString());
    }

    ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
    NextToken();
    List&amp;lt;DynamicProperty&amp;gt; properties = new List&amp;lt;DynamicProperty&amp;gt;();
    List&amp;lt;Expression&amp;gt; expressions = new List&amp;lt;Expression&amp;gt;();
    while (true) {
        int exprPos = token.pos;
        Expression expr = ParseExpression();
        string propName;
        if (TokenIdentifierIs("as")) {
            NextToken();
            propName = GetIdentifier();
            NextToken();
        }
        else {
            MemberExpression me = expr as MemberExpression;
            if (me == null) throw ParseError(exprPos, Res.MissingAsClause);
            propName = me.Member.Name;
        }
        expressions.Add(expr);
        properties.Add(new DynamicProperty(propName, expr.Type));
        if (token.id != TokenId.Comma) break;
        NextToken();
    }
    ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
    NextToken();
    Type type = anonymous ? DynamicExpression.CreateClass(properties) : class_type; 
    MemberBinding[] bindings = new MemberBinding[properties.Count];
    for (int i = 0; i &lt; bindings.Length; i++)
        bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);
    return Expression.MemberInit(Expression.New(type), bindings);
}
&lt;/pre&gt;

We will also have to add comment for the introduced exception to &lt;b&gt;Res&lt;/b&gt; class:

&lt;pre class="brush: csharp"&gt;
public const string TypeNotFound = "Type {0} not found";
&lt;/pre&gt;

Now, we are able to construct queries like following:
&lt;pre class="brush: csharp"&gt;
cars.Select("new MyApp.CarInfo(name as name, year as year, engine.type as engine_type)");
&lt;/pre&gt;

You can also nest &lt;b&gt;new&lt;/b&gt;s:
&lt;pre class="brush: csharp"&gt;
cars.Select("new MyApp.CarInfo(name, year, new EngineInfo(engine.type as type, engine.info as my_info) as engine_info)");
&lt;/pre&gt;

Of course, you can also, for example, nest typed object inside an anonymous one:
&lt;pre class="brush: csharp"&gt;
cars.Select("new (name, year, new EngineInfo(engine.type as type, engine.info as my_info) as engine_info)");
&lt;/pre&gt;

Feel free to use the modified DynamicLinq, it is uploaded to Google Code.&lt;a href="#adn3"&gt;(3)&lt;/a&gt;

&lt;div id="adns"&gt;
&lt;p id="adn1"&gt;
(1) Dynamic Linq is a part of a package available &lt;a href="http://msdn.microsoft.com/en-us/vstudio/bb894665.aspx"&gt;here&lt;/a&gt;.
&lt;p id="adn2"&gt;
(2) Dynamic Linq is described thoroughly in &lt;a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx"&gt;this&lt;/a&gt; blog post.
&lt;p id="adn3"&gt;
(3) The full modified &lt;b&gt;Dynamic.cs&lt;/b&gt; is available &lt;a href="http://code.google.com/p/dynamic-linq/"&gt;here&lt;/a&gt;. &lt;b&gt;Note:&lt;/b&gt; The version from HEAD has further updates not described here.
&lt;p id="adn4"&gt;
(4) Original StackOverflow answer where I presented the changes: &lt;a href="http://stackoverflow.com/a/8777091/1076305"&gt;Dynamic LINQ: Specifying class name in new clause&lt;/a&gt;


&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3761236184475964431-494878170161438692?l=www.krizzcode.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/anrxjD_y9yk31r6DmCCo7zXcNbY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/anrxjD_y9yk31r6DmCCo7zXcNbY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/anrxjD_y9yk31r6DmCCo7zXcNbY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/anrxjD_y9yk31r6DmCCo7zXcNbY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/KrizzsCode/~4/_5bYeqAKJ2Y" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.krizzcode.com/feeds/494878170161438692/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.krizzcode.com/2012/01/extending-dynamiclinq-language.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3761236184475964431/posts/default/494878170161438692?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3761236184475964431/posts/default/494878170161438692?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/KrizzsCode/~3/_5bYeqAKJ2Y/extending-dynamiclinq-language.html" title="Extending DynamicLINQ language: Specifying class name in &quot;new&quot; clause" /><author><name>Krzysztof Olczyk</name><uri>http://www.blogger.com/profile/02591842280854638602</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="29" src="http://4.bp.blogspot.com/-mjmhn4Rowck/TzWptG98mbI/AAAAAAAATQE/SgsPb-HGwAw/s220/me_degustation.png" /></author><thr:total>0</thr:total><feedburner:origLink>http://www.krizzcode.com/2012/01/extending-dynamiclinq-language.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0AHR3s6fip7ImA9WhRUFE8.&quot;"><id>tag:blogger.com,1999:blog-3761236184475964431.post-2770966855899444546</id><published>2012-01-23T19:52:00.005+01:00</published><updated>2012-01-24T19:28:56.516+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-24T19:28:56.516+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="lambda" /><category scheme="http://www.blogger.com/atom/ns#" term="foreach" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Closure over foreach variable in C#</title><content type="html">I have decided that I will dedicate the very first post in my brand new blog to the topic which I have noticed has pretty high coverage in StackOverflow &lt;a href="#adn1"&gt;(1)&lt;/a&gt; which I have been participating in recently. I believe it is also a case in other places where programmers exchange their knowledge.&lt;br /&gt;
&lt;br /&gt;
The typical example of the post is that the original poster is puzzled that the following piece of code does not work as they would expect it to:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var query = original_query;
foreach (var s in my_cool_strings)
{
   query = query.Where(t =&gt; t.name == s);
}
&lt;/pre&gt;&lt;br /&gt;
Let as assume that:&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;my_cool_string = new string [] { "foo", "bar" };
&lt;/pre&gt;&lt;br /&gt;
Most people will expect the constructed query to be equivalent to &lt;br /&gt;
&lt;pre class="brush: csharp"&gt;original_query.Where(t =&gt; t.name == "foo").Where(t =&gt; t.name == "bar")
&lt;/pre&gt;&lt;br /&gt;
However, it is not a case, in fact the result of the presented &lt;b&gt;foreach&lt;/b&gt; loop will be the following query:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;original_query.Where(t =&gt; t.name == "bar").Where(t =&gt; t.name == "bar")
&lt;/pre&gt;(Observe doubled &lt;b&gt;bar&lt;/b&gt; instead of &lt;b&gt;foo&lt;/b&gt;).&lt;br /&gt;
&lt;br /&gt;
If you are not familiar with the facts that:&lt;br /&gt;
1) The lambda closes &lt;b&gt;s&lt;/b&gt; by variable, not value.&lt;br /&gt;
2) The &lt;b&gt;s&lt;/b&gt; variable is external to the &lt;b&gt;foreach&lt;/b&gt; block&lt;br /&gt;
you may be surprised by it. &lt;br /&gt;
&lt;br /&gt;
Lambdas are simply constructed, not evaluated inside the block (well, this is what the lambdas are meant for). Thus, both reference the same &lt;b&gt;s&lt;/b&gt; variable - external to the block, which after loop terminates contains the value &lt;b&gt;"bar"&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
This is a case because the &lt;b&gt;foreach&lt;/b&gt; loop roughly translates to the following code:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;{
    IEnumerator&amp;lt;string&amp;gt; e = ((IEnumerable&amp;lt;string&amp;gt;)my_cool_strings).GetEnumerator();
    try
    { 
      string s; 
      while(e.MoveNext())
      {
        s = (string)e.Current;
        query = query.Where(t =&gt; t.name == s);
      }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
} 
&lt;/pre&gt;&lt;br /&gt;
The body of &lt;b&gt;while&lt;/b&gt; corresponds to the body of &lt;b&gt;foreach&lt;/b&gt; loop and we can see that the iteration variable is outside the block (line 6).&lt;br /&gt;
&lt;br /&gt;
The most common problem with this behavior is making a closure over iteration variable and it has an easy workaround:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;foreach (var s in my_cool_strings)
{
    var s_for_closure = s;
    query = query.Where(t =&gt; t.name == s_for_closure); // access to modified closure
&lt;/pre&gt;&lt;br /&gt;
Eric Lippert in his tremendous blog has posted a two-episode series of posts &lt;a href="#adn1"&gt;(2)&lt;/a&gt; describing while this design was chosen. &lt;br /&gt;
&lt;br /&gt;
Personally, the most convincing argument to me is that having new variable in each iteration would be inconsistent with for(;;) style loop as you would not expect to have a new &lt;b&gt;int i&lt;/b&gt; in each iteration of &lt;b&gt;for (int i = 0; i &lt; 10; i++)&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
Although, it is hard not to agree with the comment of &lt;a href="http://stackoverflow.com/users/691884/random832"&gt;Random832&lt;/a&gt; placed under my opionion on StackOverflow: &lt;blockquote&gt;Ultimately, what people actually want when they write this isn't to have multiple variables, it's to close over the value. And it's hard to think of a usable syntax for that in the general case.&lt;/blockquote&gt;&lt;br /&gt;
Ultimately, Eric Lippert has announced that the C# team is going to take this breaking change and C# 5 will place the loop variable logically inside the loop, rendering no longer valid what discussed in this post and making the original &lt;b&gt;foreach&lt;/b&gt; loop closure work as most people expect. &lt;a href="#adn1"&gt;(2)&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div id="adns"&gt;&lt;p id="adn1"&gt;(1) The example of StackOverflow item I was participating in: &lt;a href="http://stackoverflow.com/questions/8898925"&gt;Is there a reason for C#'s reuse of the variable in a foreach?&lt;/a&gt;.&lt;br /&gt;
&lt;p id="adn2"&gt;(2) The Eric Lippert's posts on the subject: &lt;a href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx"&gt;part one&lt;/a&gt;, &lt;a href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/16/closing-over-the-loop-variable-part-two.aspx"&gt;part two&lt;/a&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3761236184475964431-2770966855899444546?l=www.krizzcode.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/kcaW2UsYcBShRlTJirUUnbJCxxM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/kcaW2UsYcBShRlTJirUUnbJCxxM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/kcaW2UsYcBShRlTJirUUnbJCxxM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/kcaW2UsYcBShRlTJirUUnbJCxxM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/KrizzsCode/~4/4VuJqhhcEvA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.krizzcode.com/feeds/2770966855899444546/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.krizzcode.com/2012/01/closure-over-foreach-variable-in-c.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3761236184475964431/posts/default/2770966855899444546?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3761236184475964431/posts/default/2770966855899444546?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/KrizzsCode/~3/4VuJqhhcEvA/closure-over-foreach-variable-in-c.html" title="Closure over foreach variable in C#" /><author><name>Krzysztof Olczyk</name><uri>http://www.blogger.com/profile/02591842280854638602</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="29" src="http://4.bp.blogspot.com/-mjmhn4Rowck/TzWptG98mbI/AAAAAAAATQE/SgsPb-HGwAw/s220/me_degustation.png" /></author><thr:total>2</thr:total><feedburner:origLink>http://www.krizzcode.com/2012/01/closure-over-foreach-variable-in-c.html</feedburner:origLink></entry></feed>

