Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use expression tree as a code builder with a higher abstraction level then assembly emit and faster then CodeCompiler. Here is some proof of the concept that i used to convince our team to use them as a replacement for CodeCompiler.</p> <pre><code>[TestClass] public class WhenINeedToAccessPropertiesByNameHavingATypeReference { public class SomeCategoryData { public DateTime CreatedDate { get; set; } } [TestMethod] public void ICanDoThatWithAnExpressionAndItPerformsWell() { // INIT var someCategoryData = Enumerable.Range(1970, 100).Select(year =&gt; new SomeCategoryData { CreatedDate = new DateTime(year, 1, 1) }).Cast&lt;object&gt;(); var t = typeof(SomeCategoryData); // or it can be: t = someCategoryData.First().GetType(); var compiled = Stopwatch.StartNew(); // ACT var filter = AccessPropertyByNameInCompiledMannerSomehow(t, "CreatedDate"); // ASSERT Trace.WriteLine(string.Format("compiled in: {0}", compiled.Elapsed)); Assert.IsTrue(compiled.ElapsedMilliseconds &lt; 3, "compiles fast enough"); var executed = Stopwatch.StartNew(); // ACT List&lt;object&gt; result = null; for (var i = 0; i &lt; 10000; i++) { result = someCategoryData.Where(d =&gt; filter(d, new DateTime(2000, 1, 1), new DateTime(2009, 1, 1))) .ToList(); } executed.Stop(); Trace.WriteLine(string.Format("executed in: {0}", executed.Elapsed)); // ASSERT Assert.AreEqual(10, result.Count, "insure compiled code actually works"); Assert.IsTrue(executed.ElapsedMilliseconds &lt; 300, "runs fast enough"); } private static Func&lt;object, DateTime, DateTime, bool&gt; AccessPropertyByNameInCompiledMannerSomehow(Type t, string fieldToFilterBy) { var objectParameter = Expression.Parameter(typeof(object), "p"); var instance = Expression.Convert(objectParameter, t); var lower = Expression.Parameter(typeof(DateTime), "l"); var upper = Expression.Parameter(typeof(DateTime), "u"); var composite = Expression.Lambda&lt;Func&lt;object, DateTime, DateTime, bool&gt;&gt;( Expression.And( Expression.LessThanOrEqual( lower, Expression.PropertyOrField(instance, fieldToFilterBy) ), Expression.GreaterThanOrEqual( upper, Expression.PropertyOrField(instance, fieldToFilterBy) ) ), objectParameter, lower, upper ); return composite.Compile(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload