An Example of Building a LINQ Expression Tree

In the following short example, from the 101 LINQ samples, here is the basic means to constructing a basic LINQ expression, similar to how you would normally do so:
//using System;
assembly.ScopeCoercions.Add(typeof(Console).Namespace);
//using System.Linq;
assembly.ScopeCoercions.Add(typeof(Queryable).Namespace);
assembly.ScopeCoercions.Add(typeof(CultureInfo).Namespace);
var @namespace = assembly.Namespaces.Add("LinqExample");
var topLevelMethod = @namespace.Methods.Add("LinqTest");
//var digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 
var digits = topLevelMethod.Locals.Add(
        "digits",
        (new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }).ToExpression(), 
        LocalTypingKind.Implicit);
var digitSymbol = (Symbol)"digit";
/* *
 * If you know you're dealing with properties and methods,
 * use the appropriate Get* method on the expression builders
 * otherwise...
 * */

/* *
 * var sortedDigits = from digit in digits
 *                    orderby digit.Length descending,
 *                            digit[0]
 *                    select digit;
 * */
var sortedDigits = topLevelMethod.Locals.Add("sortedDigits", 
        LinqHelper
        .From("digit", /* in */ digits.GetReference())
            .OrderBy(digitSymbol.GetProperty("Length"), LinqOrderByDirection.Descending)
            .ThenBy(digitSymbol.GetIndexer(0.ToPrimitive()))
        .Select(digitSymbol).Build(), LocalTypingKind.Implicit);
topLevelMethod.DefineLocal(digits);
topLevelMethod.DefineLocal(sortedDigits);

/* *
 * Construction of expressions is pretty simple; just fuse strings together, 
 * differentiation takes place on whether the string is an expression or not.
 * */

/* *
 * Console.WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase("sorted digits"));
 * */
topLevelMethod.Call(
    "Console".Fuse("WriteLine").Fuse(
        "CultureInfo".Fuse("CurrentCulture").Fuse("TextInfo").Fuse("ToTitleCase").Fuse(
            "sorted digits".ToPrimitive())));
/* *
 * foreach (digit in sortedDigits)
 *     Console.WriteLine(digit);
 * */
var iteratorLocal = topLevelMethod.Locals.Add("digit", null, LocalTypingKind.Implicit);
iteratorLocal.AutoDeclare = false;
var enumerationBlock = topLevelMethod.Enumerate(iteratorLocal.GetDeclarationStatement(), sortedDigits.GetReference());
enumerationBlock.Call("Console".Fuse("WriteLine").Fuse(iteratorLocal.GetReference()));

Last edited Jun 22, 2011 at 2:16 PM by AlexanderMorou, version 2

Comments

No comments yet.