<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://community.bartdesmet.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>B# .NET Blog : C# 3.0, LINQ</title><link>http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/LINQ/default.aspx</link><description>Tags: C# 3.0, LINQ</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Taming Your Sequence’s Side-Effects Through IEnumerable.Let</title><link>http://community.bartdesmet.net/blogs/bart/archive/2009/09/12/taming-your-sequence-s-side-effects-through-ienumerable-let.aspx</link><pubDate>Sat, 12 Sep 2009 11:56:42 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14791</guid><dc:creator>bart</dc:creator><slash:comments>18</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14791</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2009/09/12/taming-your-sequence-s-side-effects-through-ienumerable-let.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;Side-effects don’t fit together very well with functional-style delayed computation, as observed in LINQ. Having such constructs embedded in an otherwise eagerly evaluated imperative language like C# can cause quite some confusion from time to time. A few samples (due to Erik Meijer) of such “mishaps” are shown below:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;//          &lt;br /&gt;// When does it throw?           &lt;br /&gt;//&lt;/font&gt;         &lt;br /&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;double&lt;/font&gt;&amp;gt; res = &lt;font color="#0000ff"&gt;null&lt;/font&gt;;         &lt;br /&gt;&lt;font color="#0000ff"&gt;try&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;x &lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;font color="#008080"&gt;Enumerable&lt;/font&gt;.Range(0, 10)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select &lt;/font&gt;1.0 / x;         &lt;br /&gt;}         &lt;br /&gt;&lt;font color="#0000ff"&gt;catch &lt;/font&gt;(&lt;font color="#008080"&gt;DivideByZeroException&lt;/font&gt;) {}         &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;rcp &lt;font color="#0000ff"&gt;in &lt;/font&gt;res)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(rcp);         &lt;br /&gt;        &lt;br /&gt;&lt;font color="#008000"&gt;//          &lt;br /&gt;// What does it print?           &lt;br /&gt;//           &lt;br /&gt;&lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;bool&lt;/font&gt;&amp;gt; div2 = i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;“Div2 test “&lt;/font&gt; + i); &lt;font color="#0000ff"&gt;return &lt;/font&gt;i % 2 == 0; };         &lt;br /&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;bool&lt;/font&gt;&amp;gt; div3 = i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;“Div3 test “ &lt;/font&gt;+ i); &lt;font color="#0000ff"&gt;return &lt;/font&gt;i % 3 == 0; };         &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;x &lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;font color="#008080"&gt;Enumerable&lt;/font&gt;.Range(0, 10)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;where &lt;/font&gt;div2(x)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;where &lt;/font&gt;div3(x)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select &lt;/font&gt;x;         &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;sxt &lt;font color="#0000ff"&gt;in &lt;/font&gt;res)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(sxt);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The side-effects in the samples above are of various kinds: exceptions and output operations all hurt in a functional setting. In pure “fundamentalist” functional programming languages, those effects are made explicit by means of the type system (in particular, the IO monad). When looking at a .NET “function” signature, types are lying at us:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier new"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public int &lt;/font&gt;Next();         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Sure, Next returns an Int32 numeric value when being called. But that’s only part of the story: every time you call it, it may return something else. In other words, we can’t simplify the following program:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;rand = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();         &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;fems = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Pair&lt;/font&gt;(rand.Next(), rand.Next());&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;into&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;rand = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();       &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;__rn = rand.Next();       &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;fems = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Pair&lt;/font&gt;(__rn, __rn);&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;The main reason is simply because we don’t know enough about the behavior, i.e. the side-effects, the Next function exposes. Or to state it in another manner, Next is not a (pure) &lt;em&gt;function&lt;/em&gt; but a &lt;em&gt;method&lt;/em&gt;. In Haskell, types tell us a side-effect is going on:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="courier New"&gt;randomIO :: (&lt;font color="#008080"&gt;Random &lt;/font&gt;a) =&amp;gt; &lt;strong&gt;IO&lt;/strong&gt; a&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Roughly speaking, Random a stands for Random&amp;lt;T&amp;gt; and IO a stands for T, “tagged” with the fact it has a side-effect through the IO monad (not the same as IO&amp;lt;T&amp;gt; as the CLR’s type system doesn’t support the &lt;a href="http://www.cs.kuleuven.be/~adriaan/files/higher.pdf"&gt;higher kinding&lt;/a&gt; required to realize the typing required for monads).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Multiplication of side-effects&lt;/h1&gt;  &lt;p&gt;Being aware of the presence of side-effects is one thing, having them amplified or multiplied (almost) invisibly through the use of query combinators and such is even more painful. Consider the following iterator:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;RandomExtensions&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; GetNumbers(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#008080"&gt;Random &lt;/font&gt;rand, &lt;font color="#0000ff"&gt;int &lt;/font&gt;max)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(&lt;font color="#0000ff"&gt;true&lt;/font&gt;)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;rand.Next(max);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;which can be called like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; rand = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();         &lt;br /&gt;&lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;x &lt;font color="#0000ff"&gt;in &lt;/font&gt;rand.GetNumbers(100).Take(10))         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(x);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;All is good and well so far, we’ll get 10 random numbers printed to the screen. Now assume we’re already in .NET 4 (just to make illustration a little easier, the general topic of “taming side effects” is version-independent and platform(-excluding-Haskell)-independent) and have &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx"&gt;Zip method&lt;/a&gt; available. Let’s write the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;rand = &lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();&lt;/font&gt;       &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;&lt;/font&gt;res = &lt;strong&gt;rand.GetNumbers(100).Take(10)&lt;/strong&gt;.Zip(&lt;strong&gt;rand.GetNumbers(100).Take(10)&lt;/strong&gt;, (l, r) =&amp;gt; l + r).All(x =&amp;gt; x % 2 == 0);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What do you think res should be? Clearly, the sum of a number and itself is always even. In bold, we have a common subexpression: on the face of it, you may think it’d produce the same results for both “sides” of Zip, hence the conclusion the zipped sums should always be even. Nothing is further away from the truth: GetNumbers propagates the side-effect of the underlying IO operation (reading form a random number generator) and the two calls create separate iterator instances, each merrily ticking along. A simple Print operator can help to illustrate this:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; Print&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#0000ff"&gt;string&lt;/font&gt; formatMessage)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;item &lt;font color="#0000ff"&gt;in &lt;/font&gt;source)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(formatMessage, item);       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;item;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;Yes, even more side-effects added to the melting pot. Now we can write the following to illustrate the mishap:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;rand = &lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();&lt;/font&gt;     &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;&lt;/font&gt;res = &lt;strong&gt;rand.GetNumbers(100).Take(10)&lt;/strong&gt;.Print(&lt;font color="#800000"&gt;“SRC1: {0}”&lt;/font&gt;).Zip(&lt;strong&gt;rand.GetNumbers(100).Take(10)&lt;/strong&gt;.Print(&lt;font color="#800000"&gt;“SRC2: {0}”&lt;/font&gt;), (l, r) =&amp;gt; l + r).All(x =&amp;gt; x % 2 == 0);&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;One run on the author’s machine produced:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier new"&gt;SRC1: 82        &lt;br /&gt;SRC2: 86         &lt;br /&gt;SRC1: 17         &lt;br /&gt;SRC2: 91         &lt;br /&gt;SRC1: 48         &lt;br /&gt;SRC2: 15&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Clearly, both sources are out of sync. Now we go and knock on the door of a fellow programmer and ask to solve this issue. Well, &lt;em&gt;clearly&lt;/em&gt; you’re calling GetNumbers twice – that’s your problem right there. Not so much… Let’s see what a proposed fix would look like:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;rand = &lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();       &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;src = rand.GetNumbers(100).Take(10);&lt;/font&gt;     &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;&lt;/font&gt;res = src.Print(&lt;font color="#800000"&gt;“SRC1: {0}”&lt;/font&gt;).Zip(src.Print(&lt;font color="#800000"&gt;“SRC2: {0}”&lt;/font&gt;), (l, r) =&amp;gt; l + r).All(x =&amp;gt; x % 2 == 0);&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;And here’s the result:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;SRC1: 89        &lt;br /&gt;SRC2: 39         &lt;br /&gt;SRC1: 22         &lt;br /&gt;SRC2: 15&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What’s happening here? Although we’ve reduced the number of calls to GetNumbers to just a single one, its execution is still lazily evaluated as we’re using an iterator. It’s not until we start iterating that computation is triggered. Moreover, the iterator returns an IEnumerable&amp;lt;int&amp;gt; which merely provides the &lt;em&gt;potential&lt;/em&gt; to enumerate though the IEnumerator&amp;lt;int&amp;gt; objects it hands out. In effect, Zip will call GetEnumerator twice, resulting in two instances of the iterator (simplified code below):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;R&amp;gt; Zip&amp;lt;T1, T2, R&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T1&amp;gt; left, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T2&amp;gt; right, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T1, T2, R&amp;gt; zip)         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;leftE = left.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;rightE = right.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(leftE.MoveNext() &amp;amp;&amp;amp; rightE.MoveNext())         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;zip(leftE.Current, rightE.Current);         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In our case, left and right are pretty much the same (ignore Print which acts as an all-pass filter iterator), namely src:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;src.Zip(src, …)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Two calls to GetEnumerator result, each querying the same random generator instance that happily continues on its side-effecting mission. The iterator we wrote for GetNumbers is semantically equivalent to the following, illustrating this issue more clearly for those who are not familiar with the way iterators are compiled (simplified presentation):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;RandomExtensions&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; GetNumbers(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#008080"&gt;Random &lt;/font&gt;rand, &lt;font color="#0000ff"&gt;int &lt;/font&gt;max)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return new &lt;/font&gt;GetNumbersIterator(rand, max);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}         &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;GetNumbersIterator &lt;/font&gt;: &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;Random &lt;/font&gt;_rand;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private int &lt;/font&gt;_max;         &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;GetNumbersIterator(&lt;font color="#008080"&gt;Random &lt;/font&gt;rand, &lt;font color="#0000ff"&gt;int &lt;/font&gt;max)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _rand = rand;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _max = max;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; GetEnumerator()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return new &lt;/font&gt;&lt;font color="#008080"&gt;GetNumbersIteratorEnumerator&lt;/font&gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt;);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;GetNumbersIteratorEnumerator &lt;/font&gt;: &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;GetNumbersIterator &lt;/font&gt;_iter;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private int &lt;/font&gt;_curr;         &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;GetNumbersIteratorEnumerator(&lt;font color="#008080"&gt;GetNumbersIterator &lt;/font&gt;iter)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _iter = iter;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public bool &lt;/font&gt;MoveNext()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _curr = _iter._rand.Next(_iter._max);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return true&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public int &lt;/font&gt;Current         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;get &lt;/font&gt;{ &lt;font color="#0000ff"&gt;return &lt;/font&gt;_curr; }&lt;/font&gt;&lt;font face="Courier New"&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In fact, you could say the side-effect that’s killing us now is the instantiation of GetNumbersIteratorEnumerator inside the GetEnumerator method. Observing that, the innocent unenlightened developer may say: what if we eliminate that additional object instantiation? Let’s “desugar” the iterator by writing it as the thing above (quite a bit of work, but the innocent developer is willing to go great lengths to get his code working As The Natural Numbers Intended) and eliminating the construction of a new GetNumbersIteratorEnumerator all the time.&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;GetNumbersIterator &lt;/font&gt;: &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;Random &lt;/font&gt;_rand;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private int &lt;/font&gt;_max;       &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; private &lt;/font&gt;&lt;font color="#008080"&gt;GetNumbersIteratorEnumerator&lt;/font&gt; _curr;       &lt;br /&gt;      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;GetNumbersIterator(&lt;font color="#008080"&gt;Random &lt;/font&gt;rand, &lt;font color="#0000ff"&gt;int &lt;/font&gt;max)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _rand = rand;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _max = max;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _curr = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;GetNumbersIteratorEnumerator&lt;/font&gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt;);       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; GetEnumerator()       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;_curr;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;Guess what? Here’s the result:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;SRC1: 15        &lt;br /&gt;SRC2: 97         &lt;br /&gt;SRC1: 31         &lt;br /&gt;SRC2: 57         &lt;br /&gt;SRC1: 21         &lt;br /&gt;SRC2: 57         &lt;br /&gt;SRC1: 63         &lt;br /&gt;SRC2: 94&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Bummer. We’re just pushing the problem in front of us. Though we have the same enumerator object inside the Zip method now, we’re still calling MoveNext twice:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;R&amp;gt; Zip&amp;lt;T1, T2, R&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T1&amp;gt; left, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T2&amp;gt; right, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T1, T2, R&amp;gt; zip)       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;leftE = left.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;rightE = right.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Debug&lt;/font&gt;.Assert(leftE == rightE);       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(leftE.&lt;strong&gt;MoveNext() &lt;/strong&gt;&amp;amp;&amp;amp; rightE.&lt;strong&gt;MoveNext()&lt;/strong&gt;)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;zip(leftE.Current, rightE.Current);       &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;What would the desperate developer’s next suggestion be? Let’s not go there – clearly there’s something bigger the matter here. Everything you try at this level of decomposing iterator objects and knowing precisely how query operators work is a very very ugly band-aid trying to cover up for the bigger problem of side-effect replication here.&lt;/p&gt;  &lt;p&gt;One way to tackle the problem from the outside is to break laziness:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;rand = &lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();       &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;src = rand.GetNumbers(100).Take(10)&lt;strong&gt;.ToArray()&lt;/strong&gt;;&lt;/font&gt;     &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;&lt;/font&gt;res = src.Print(&lt;font color="#800000"&gt;“SRC1: {0}”&lt;/font&gt;).Zip(src.Print(&lt;font color="#800000"&gt;“SRC2: {0}”&lt;/font&gt;), (l, r) =&amp;gt; l + r).All(x =&amp;gt; x % 2 == 0);&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;Operators like ToArray and ToList drain the left-hand side sequence on the spot, persisting the retrieved elements in-memory. Iterators versus persisted data sequences aren’t differentiated on the type level: both are “enumerable”. Great from a generalization point of view, less so to understand the runtime behavior of dealing with those objects. Either way, the above works and prints:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;SRC1: 44        &lt;br /&gt;SRC2: 44         &lt;br /&gt;SRC1: 6         &lt;br /&gt;SRC2: 6         &lt;br /&gt;SRC1: 81         &lt;br /&gt;SRC2: 81         &lt;br /&gt;SRC1: 14         &lt;br /&gt;SRC2: 14         &lt;br /&gt;SRC1: 65         &lt;br /&gt;SRC2: 65         &lt;br /&gt;SRC1: 1         &lt;br /&gt;SRC2: 1         &lt;br /&gt;SRC1: 9         &lt;br /&gt;SRC2: 9         &lt;br /&gt;SRC1: 67         &lt;br /&gt;SRC2: 67         &lt;br /&gt;SRC1: 65         &lt;br /&gt;SRC2: 65         &lt;br /&gt;SRC1: 75         &lt;br /&gt;SRC2: 75&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;For the first time we reached the end of the zipped sequence. Wonderful. But we’ve made a big sacrifice, something I accounted for right from the start of the post by using Take(10). The above doesn’t work if we’re dealing with &lt;strong&gt;infinite sequences&lt;/strong&gt;. Obviously you should never try to drain those as the program will get stuck (which in fact can be formalized as well, maybe stuff to cover another time), yet infinite sequences are great to provide the user with the potential to compute as many results as desired. Having to break laziness to make query operator composition, e.g. for Zip in our sample, work spoils this whole idea of lazy computation.&lt;/p&gt;  &lt;p&gt;By now it should be clear that side-effects are have far-stretching implications, but we should not ignore the fact they’re useful &lt;em&gt;at times&lt;/em&gt;. What we need to make our “consistent consumption of side-effectful sequences” is some kind of &lt;strong&gt;let&lt;/strong&gt; construct.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;What’s let anyway?&lt;/h1&gt;  &lt;p&gt;Functional programming languages typically provide a “let” construct, e.g. as seen in ML-style languages like F#. One form is to use the following syntax:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;let &lt;/font&gt;&lt;font color="#008000"&gt;id &lt;/font&gt;&lt;font color="#0000ff"&gt;= expr1 &lt;/font&gt;&lt;font color="#ff0000"&gt;in&lt;/font&gt; expr2&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The above is shorthand for &lt;em&gt;abstraction &lt;/em&gt;and &lt;em&gt;application &lt;/em&gt;carried out right after one another:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;(&lt;/font&gt;&lt;font color="#ff0000"&gt;fun &lt;/font&gt;&lt;font color="#008000"&gt;id &lt;/font&gt;&lt;font color="#ff0000"&gt;–&amp;gt; &lt;/font&gt;expr2&lt;font color="#0000ff"&gt;)&lt;/font&gt; &lt;font color="#0000ff"&gt;expr1&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Consider the next sample:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;let &lt;/font&gt;&lt;font color="#008000"&gt;x&lt;/font&gt; &lt;font color="#0000ff"&gt;= 1&lt;/font&gt; &lt;font color="#ff0000"&gt;in&lt;/font&gt; (x, x)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where (…, …) is the tupling operator. Semantically the above is equivalent to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;(&lt;/font&gt;&lt;font color="#ff0000"&gt;fun&lt;/font&gt; &lt;font color="#008000"&gt;x&lt;/font&gt;&amp;#160;&lt;font color="#ff0000"&gt;–&amp;gt; &lt;/font&gt;(x, x)&lt;font color="#0000ff"&gt;) 1&lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In a call-by-value setting this effectively avoids re-evaluating the &lt;em&gt;expr1 &lt;/em&gt;expression. Of course in the sample above, there’s not much work required to “re-evaluate” the rather minimalistic expression “1”. However, when evaluating this expression causes side-effects, we’re eliminating duplicate evaluation. This is shown in the sample below where we use the Stopwatch type to retrieve the timestamp, based on a high-resolution performance counter (see MSDN documentation for information and potential caveats).&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb.png" width="677" height="366" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Of course we can loop in our Random type sample as well:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_3.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_3.png" width="677" height="270" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You get the idea. How does this apply to our side-effecting iterators? Well, what we really want is a mechanism by which we can expose the same iterator to multiple consumers without re-evaluating the side-effects that get triggered by calls to IEnumerator.MoveNext (where the iterator’s code lives in one form or another). In addition to this functional requirement, we can’t drain the whole iterator as we’d break our teeth on infinite (computed) sequences.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;IEnumerable.Let – Signature and use&lt;/h1&gt;  &lt;p&gt;First, let’s have a look at the contract for the IEnumerable.Let operator we’re after here. Obviously we want to keep the order as natural as possible and what better to use than an extension method to make syntax as natural as possible:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;… Let&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, …)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;That’s a good start: we can take in an IEnumerable&amp;lt;T&amp;gt; as the &lt;em&gt;expr1&lt;/em&gt; for the let construct. Looking back at the F# equivalent for a moment:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;(&lt;/font&gt;&lt;font color="#ff0000"&gt;fun &lt;/font&gt;&lt;font color="#008000"&gt;id &lt;/font&gt;&lt;font color="#ff0000"&gt;–&amp;gt; &lt;/font&gt;expr2&lt;font color="#0000ff"&gt;)&lt;/font&gt; &lt;font color="#0000ff"&gt;expr1&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;It’s clear we need to have a function that exposes the one-time evaluated (read: enumerated) to a block of code where the user can party on the exposed sequence without having to worry about duplicating side-effects. The input of such a function clearly is IEnumerable&amp;lt;T&amp;gt;, leading to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;… Let&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt;, …&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So, “id” from the F# code sample above will be identified to the input of the Func delegate. Finally, what’s the output meant to be? Obviously just the output of the expr2 evaluation after feeding in expr1 through the parameter. As we’re talking about sequence operators, a natural choice is to make the output an IEnumerable as well, and to allow projections and such to happen inside we choose another generic parameter:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;… Let&amp;lt;T, U&amp;gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt;, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;U&amp;gt;&amp;gt; function)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You can guess where the output of the source is meant to go to: the output of the Let construct by itself:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;U&amp;gt; Let&amp;lt;T, U&amp;gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt;, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;U&amp;gt;&amp;gt; function)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Makes sense? For example, for our fancy Zip over random sequence we want to be able to write the following:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;rand = &lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;/font&gt;&lt;font color="#008080"&gt;Random&lt;/font&gt;();&lt;/font&gt;     &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;&lt;/font&gt;res = &lt;strong&gt;rand.GetNumbers(100).Take(10)&lt;/strong&gt;.Let(&lt;strong&gt;nums &lt;/strong&gt;=&amp;gt; &lt;strong&gt;nums&lt;/strong&gt;.Zip(&lt;strong&gt;nums&lt;/strong&gt;, (l, r) =&amp;gt; l + r)).All(x =&amp;gt; x % 2 == 0);&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;See what’s happening here? The left-hand side to Let becomes the source, which internally is exposed as “nums”. Zip produces its output, which becomes the output of the Let construct that’s subsequently fed into All. In fact, the above could be read as:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;&lt;/font&gt;res = (&lt;font color="#0000ff"&gt;let &lt;/font&gt;nums = &lt;strong&gt;rand.GetNumbers(100).Take(10) &lt;font color="#0000ff"&gt;in&lt;/font&gt;           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; nums&lt;/strong&gt;.Zip(&lt;strong&gt;nums&lt;/strong&gt;, (l, r) =&amp;gt; l + r))         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .All(x =&amp;gt; x % 2 == 0);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now on to the question of the night, how to realize this?&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Implementing IEnumerable.Let&lt;/h1&gt;  &lt;p&gt;Before we start implementing the let construct for LINQ to Objects, we need to make sure we fully understand the problem. &lt;em&gt;Let &lt;/em&gt;me rephrase it one more time:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Given an IEnumerable&amp;lt;T&amp;gt; source, we need to &lt;em&gt;expose &lt;/em&gt;it to a function is such a way that multiple consumers can only trigger a &lt;em&gt;single enumerator &lt;/em&gt;to be active on the source. This ensures that the side-effects occurring as part of the enumeration (using MoveNext/Current) over the enumerator are not replicated.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Since many consumers can be active inside the “let body” (the &lt;em&gt;function&lt;/em&gt; parameter in the signature), we can expect those to move at different paces. Here’s an example:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;nums.Skip(5).Zip(nums, …)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In here, the Skip operator readily advances the iteration over the source 5 positions ahead. Then Zip consumes this input as well as the raw source starting from position 0. Given a sequence of { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, the inputs to Zip are skewed over a distance 5, combining (6, 1), (7, 2), etc. This forces us to &lt;em&gt;memorize&lt;/em&gt; the first 5 elements that have already been consumed by Skip, as they still have to be observed through Zip’s second input (and obviously we can’t recompute them as that’s what we’re trying to eliminate!).&lt;/p&gt;  &lt;p&gt;For one thing, we need to keep track of elements that have been consumed from the Let-source so that consumers inside the body can get access to those computed values. An immediate question becomes whether or not we can optimize this: wouldn’t it be possible to scavenge the computed values if we are sure no single consumer inside the body can still consume it? Sounds reasonable, but there’s a deep problem here: the number of consumers can be dynamic. A good sample is SelectMany:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;x &lt;font color="#0000ff"&gt;in &lt;/font&gt;nums         &lt;br /&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;y &lt;font color="#0000ff"&gt;in &lt;/font&gt;nums         &lt;br /&gt;&lt;font color="#0000ff"&gt;select &lt;/font&gt;x + y&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This translates into the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;nums.SelectMany(x =&amp;gt; nums, (x, y) =&amp;gt; x + y)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;SelectMany is conceptually similar to nested loops used to enumerate a collection and for each of its elements retrieve associated objects (e.g. for each product, and each order for that product, do …). In the sample above we use nums twice, so assuming the source looks like { 1, … , 9 }, we will see the following pairs being fed to the projection function parameter:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;(1, 1), (1, 2), …, (1, 9), (2, 1), …, (9, 1), (9, 2), …, (9, 9)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;For the 9 elements in the left-hand side source, we’ll enumerate all of the elements in the corresponding source found by evaluating x =&amp;gt; nums (where, in this degenerate case, we disregard the parameter x and simply return ourselves). How many times will we trigger enumeration on nums here? Well, one time for the input to SelectMany as the left-hand side, and for each element one more time for the nested enumeration. So, with 9 elements, the total will be 9 + 1 = 10. There’s no way for us to know upfront how many subscriptions will happen, so we can’t make assumptions when we can discard elements we’ve retrieved from the source.&lt;/p&gt;  &lt;p&gt;All of those observations give rise to the introduction of a &lt;strong&gt;“memoized enumerator”&lt;/strong&gt;. A what? Memoization is a technique used in functional programming to cache the result of evaluating a function knowing that function is &lt;em&gt;pure&lt;/em&gt;, i.e. given the same inputs it always gives back the same output. A typical example is recursive Fibonacci:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;uint&lt;/font&gt;, &lt;font color="#0000ff"&gt;uint&lt;/font&gt;&amp;gt; fib = &lt;font color="#0000ff"&gt;null&lt;/font&gt;;         &lt;br /&gt;fib = n =&amp;gt; n &amp;lt;= 1 ? 1 : fib(n - 2) + fib(n - 1);         &lt;br /&gt;&lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;uint &lt;/font&gt;i = 0; i &amp;lt; 50; i++)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fib(i));&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Good luck running this code – it will take forever to compute fib(50) (ignore the fact it doesn’t fit in a uint) due to the explosion of recursive steps and re-evaluations incurred. A generic memoization function will cache results:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static&lt;/font&gt; &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, R&amp;gt; Memoize&amp;lt;T, R&amp;gt;(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, R&amp;gt; f)         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;cache = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Dictionary&lt;/font&gt;&amp;lt;T, R&amp;gt;(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;t =&amp;gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; R res;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(cache.TryGetValue(t, &lt;font color="#0000ff"&gt;out &lt;/font&gt;res))         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;res;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;cache[t] = f(t);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; };         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This memoizer is a higher-order function that transparently (in terms of the function signature) maps a function onto one that caches evaluation results. As a result, for a given function input “t”, the function “f” can be evaluated at most once (for subsequent function calls given the same input, the dictionary will be consulted). It should be pretty clear this is precisely what we want for our Let-enumerator as well, but instead of keying off the avoidance for multiple evaluations from the function input, we’ll need to avoid it based on the position of an enumerator. Let’s discuss this.&lt;/p&gt;  &lt;p&gt;Assume you have two consumers of the Let-input sequence: one skips ahead 5 positions, the other starts from the beginning, just as we saw before:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;src.Let(nums =&amp;gt; nums.Skip(5).Zip(nums, (l, r) =&amp;gt; l + r))&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Let’s decompose the interactions here. Zip is pulling both its left-hand side followed by its first parameter, at an equal pace. First, the end-result:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_4.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_4.png" width="400" height="253" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I hope the above diagram makes sense, if not look at the more conceptual diagram below:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_5.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_5.png" width="400" height="112" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now we loop bottom-up: if something pulls at Zip, what does it start pulling at by itself? First it calls MoveNext on its left-hand side, which is the Skip(5) block. Skip starts by fetching the first 5 + 1 items from its input, which is the Let block, in order to yield the 6th item back to the consumer. This leads to the following situation:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_6.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_6.png" width="400" height="273" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The read arrows indicate the active “channels” of enumeration. Reading bottom-up, Zip requested one element from Skip(5), which on its drew 6 items through its upstream channel connected to Let. Since Let hasn’t received calls to retrieve elements from the source at positions 0 through 5, it pulled on its source to get those items, causing &lt;strong&gt;potential side-effects&lt;/strong&gt; (indicated by the bombs). But beside just yielding them back to the Skip(5) caller, it also “memoizes” them in an indexed collection. The “@5” annotation on the outgoing Let arrows – representing enumerators – indicate the cursor position in the source sequence, of the element that was last yielded through the channel.&lt;/p&gt;  &lt;p&gt;Now that Zip has an element from its left-hand side source, it needs to fetch an element from its right-hand side source, in order for the two elements to be combined by the zipper function (in our case numerical +). This looks as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_7.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_7.png" width="400" height="253" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice the red channel doesn’t extend all the way to the source – we already have received the element at position 0, so we can consult the memoization store to retrieve the value from there. &lt;strong&gt;No observable source-induced side-effects are triggered by doing so.&lt;/strong&gt; The cursor position for the active Let-consumer is moved to 0.&lt;/p&gt;  &lt;p&gt;Essentially, whenever a channel queries for an element below the high-water mark of the memoization store, the element are retrieved from the store instead of pulling from the source. On to the code now. We’ll start by looking at a memoizing enumerable as we’ll use that as the building block for the Let construct. First, the IEnumerable&amp;lt;T&amp;gt; implementation:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;, &lt;span style="color:#2b91af;"&gt;IDisposable
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private readonly &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; _source;
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IList&lt;/span&gt;&amp;lt;T&amp;gt; _data;
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;T&amp;gt; _enumSource;
    &lt;span style="color:blue;"&gt;private bool &lt;/span&gt;_disposed;
    &lt;span style="color:blue;"&gt;private bool &lt;/span&gt;_reachedEnd;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;MemoizeEnumerable(&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source)
    {
        _source = source;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;T&amp;gt; GetEnumerator()
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_disposed)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ObjectDisposedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;LetIterator&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_enumSource == &lt;span style="color:blue;"&gt;null&lt;font color="#333333"&gt; &amp;amp;&amp;amp; !_reachedEnd)&lt;/font&gt;&lt;/span&gt;
        {
            _enumSource = _source.GetEnumerator();
            _data = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();
        }

        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerator&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this&lt;/span&gt;);
    }

    System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerator &lt;/span&gt;System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;.GetEnumerator()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;GetEnumerator();
    }

    &lt;span style="color:blue;"&gt;private bool &lt;/span&gt;TryMoveNext(&lt;span style="color:blue;"&gt;int &lt;/span&gt;cursor, &lt;span style="color:blue;"&gt;out &lt;/span&gt;T value)
    {
        &lt;span style="color:#2b91af;"&gt;Debug&lt;/span&gt;.Assert(cursor &amp;lt;= _data.Count);

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_disposed)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ObjectDisposedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;LetIterator&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(cursor &amp;lt; _data.Count)
        {
            value = _data[cursor];
            &lt;span style="color:blue;"&gt;return true&lt;/span&gt;;
        }
        &lt;span style="color:blue;"&gt;else
        &lt;/span&gt;{
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_reachedEnd)
            {
                value = &lt;span style="color:blue;"&gt;default&lt;/span&gt;(T);
                &lt;span style="color:blue;"&gt;return false&lt;/span&gt;;
            }

            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_enumSource.MoveNext())
            {
                value = _enumSource.Current;
                _data.Add(value);
                &lt;span style="color:blue;"&gt;return true&lt;/span&gt;;
            }
            &lt;span style="color:blue;"&gt;else
            &lt;/span&gt;{
                &lt;span style="color:green;"&gt;// When we reach the end, no reason to delay the disposal of the source
                // any longer. Now we should avoid calls to MoveNext further on, so we
                // set a _reachedEnd flag to detect this case.
                &lt;/span&gt;_enumSource.Dispose();&lt;br /&gt;                _enumSource = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;
                _reachedEnd = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;

                value = &lt;span style="color:blue;"&gt;default&lt;/span&gt;(T);&lt;br /&gt;                &lt;span style="color:blue;"&gt;return false&lt;/span&gt;;
            }
        }
    }

    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Dispose()
    {
        &lt;span style="color:green;"&gt;// Facilitates deterministic disposal of the underlying store. We can&amp;#39;t rely
        // on Dispose calls on the enumerator object as we don&amp;#39;t know the number of
        // consumers we&amp;#39;re dealing with.
        &lt;/span&gt;&lt;span style="color:blue;"&gt;if &lt;/span&gt;(!_reachedEnd)&lt;br /&gt;        {
            _enumSource.Dispose();
            _enumSource = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;&lt;br /&gt;        }&lt;br /&gt;
        _disposed = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
        _data.Clear();
    }

    &lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerator&lt;/span&gt;&amp;lt;T_&amp;gt; : &lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;T_&amp;gt;
    {
        …&lt;br /&gt;    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;A MemoizeEnumerable&amp;lt;T&amp;gt; encapsulates an underlying IEnumerable&amp;lt;T&amp;gt; that represents the source. The GetEnumerator method for consumers to call in order to establish an enumerator triggers the MemoizeEnumerable to start consuming the input source unless it’s already doing so. This is the key to avoiding multiple source-consumers, which would lead to duplication of side-effects. The memoization store is simply a List&amp;lt;T&amp;gt;, which is indexable. What the MemoizeEnumerator&amp;lt;T&amp;gt; looks like will be shown soon.&lt;/p&gt;

&lt;p&gt;Skipping over TryMoveNext for just a second, we look at Dispose first. As we’ve seen before, the number of enumerators over the exposed memoized data structure is something we can’t know upfront or infer from context. So, the disposal of enumerator objects doesn’t mean we can dispose the enumerator we established on the (memoized) source. We need a hint from the outside to say: it’s fine to let go the source (which could be holding on to, say, a network connection underneath). This will correspond to “scoped usage” of the Let construct as we shall see later.&lt;/p&gt;

&lt;p&gt;Now on to TryMoveNext. Here the fetching of the underlying source happens, based on a passed-in cursor. We enforce linear progression, which is expected for MoveNext calls: the consuming enumerators should at most take one step forward at a time. If the cursor falls within the range of the memoization store, we simply retrieve the cached value from there. Otherwise, we fetch the next element from the underlying source (causing a potential side-effect once and for all for that element) and keep it in the store. If there are no further elements to be fetched as signaled by the source’s MoveNext call’s return value, we can dispose the enumerator over the source. To avoid subsequent calls on the disposed object, we keep a flag to signal we’ve reached the end. Notice we’re not dealing with multi-threaded consumers here – such worries are left as an exercise for the reader.&lt;/p&gt;

&lt;p&gt;Finally, we should have a look at the MemoizeEnumerator inner class which obviously will call TryMoveNext in order to make progress over the shared source enumerator and memoization store. This type is fairly trivial:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerator&lt;/span&gt;&amp;lt;T_&amp;gt; : &lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;T_&amp;gt;
{
    &lt;span style="color:blue;"&gt;private readonly &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerable&lt;/span&gt;&amp;lt;T_&amp;gt; _source;
    &lt;span style="color:blue;"&gt;private int &lt;/span&gt;_cursor;
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;T_ _lastValue;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;MemoizeEnumerator(&lt;span style="color:#2b91af;"&gt;MemoizeEnumerable&lt;/span&gt;&amp;lt;T_&amp;gt; source)
    {
        _source = source;
        _cursor = 0;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;T_ Current
    {
        &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;_lastValue; }
    }

    &lt;span style="color:blue;"&gt;object &lt;/span&gt;System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;.Current
    {
        &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;Current; }
    }

    &lt;span style="color:blue;"&gt;public bool &lt;/span&gt;MoveNext()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_source.TryMoveNext(_cursor++, &lt;span style="color:blue;"&gt;out &lt;/span&gt;_lastValue);
    }

    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Reset()
    {
        _cursor = 0;
    }

    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Dispose()
    {
        &lt;span style="color:green;"&gt;// No disposal here - the enumerable object does the bookkeeping of the
        // underlying enumerator object. Here we&amp;#39;re essentially just dealing with
        // a cursor into the underlying sequence.
    &lt;/span&gt;}
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;All there is to a memoizing enumerator is to keep its cursor, communicate it to TryMoveNext, and increment it. Notice the assert in TryMoveNext will trigger when an ill-behaved consumer continues to call MoveNext on the enumerator after it has returned false. One could pimp this case a little bit by either keeping a _reachedEnd state inside the enumerator (not to bother the enumerable object anymore in such a case) or by keeping the _cursor value in its final position as opposed to incrementing it.&lt;/p&gt;

&lt;p&gt;Notice the enumerator’s Dispose method is not implemented for reasons explained earlier. The only thing one could do as a meaningful implementation is a _disposed flag to throw an ObjectDisposedException if the object is used beyond its disposal state. We leave this as a trivial exercise for the reader as well.&lt;/p&gt;

&lt;p&gt;Ultimately we’ve reached a state where we can give away the entry-point to IEnumerable.Let:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;U&amp;gt; Let&amp;lt;T, U&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; function)
{
    &lt;span style="color:blue;"&gt;using &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;mem = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;(source))
    {
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;item &lt;span style="color:blue;"&gt;in &lt;/span&gt;function(mem))
            &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;item;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The most important thing here is obviously the memoization of the source which is fed to the function for the let-body to party on. The use of a using-block inside an iterator causes that iterator’s Dispose method to call the Dispose method on the resource in use. In other words, if one foreach’es over the result of a Let-call, exiting the loop will trigger a call to Dispose which on its turn disposes the memoized enumerable, again on its turn disposing the underlying source’s singleton enumerator. This means re-executing the Let resulting sequence itself will cause re-iteration over the underlying source. This makes sense as we only protect against duplication of side-effects &lt;em&gt;inside&lt;/em&gt; the let-body. If you want to avoid re-execution of the Let-operator to cause duplication of side-effects by itself, wrap it in yet another Let-call.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;A few samples&lt;/h1&gt;

&lt;p&gt;Time for some samples to conclude this journey. We go for two source iterators that are only of interest for their side-effects:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; GetNums(&lt;span style="color:blue;"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color:blue;"&gt;try
    &lt;/span&gt;{
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt;= n; i++)
        {
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ForegroundColor = &lt;span style="color:#2b91af;"&gt;ConsoleColor&lt;/span&gt;.Red;
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.Write(i + &lt;span style="color:#a31515;"&gt;&amp;quot;   &amp;quot;&lt;/span&gt;);
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ResetColor();
            &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;i;
        }
    }
    &lt;span style="color:blue;"&gt;finally
    &lt;/span&gt;{
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ForegroundColor = &lt;span style="color:#2b91af;"&gt;ConsoleColor&lt;/span&gt;.Green;
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Disposed&amp;quot;&lt;/span&gt;);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ResetColor();
    }
}

&lt;span style="color:blue;"&gt;static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random &lt;/span&gt;rand = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;();

&lt;span style="color:blue;"&gt;static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; Lotto()
{
    &lt;span style="color:blue;"&gt;try
    &lt;/span&gt;{
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; 6; i++)
        {
            &lt;span style="color:blue;"&gt;var &lt;/span&gt;n = rand.Next(100);
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ForegroundColor = &lt;span style="color:#2b91af;"&gt;ConsoleColor&lt;/span&gt;.Red;
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(n);
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ResetColor();
            &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;n;
        }
    }
    &lt;span style="color:blue;"&gt;finally
    &lt;/span&gt;{
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ForegroundColor = &lt;span style="color:#2b91af;"&gt;ConsoleColor&lt;/span&gt;.Green;
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Disposed&amp;quot;&lt;/span&gt;);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ResetColor();
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;We log produced values to the console to visualize how many times the iterator is enumerated over. Obviously we write those in red as they are bloody side-effects. We’re also interested to see proper disposal, so we log that event too. A first example using SelectMany without Let shows how bad things get as we replicate side-effects:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Without let&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;source = GetNums(10);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;source
              &lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;source
              &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + y;

    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;i &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
        ;
}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The result is as follows, no less than 11 iterations over the source sequence:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_8.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_8.png" width="472" height="164" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Next, we eliminate the common sub-expression “source” by lifting it into a Let block. Source becomes the input to Let, and inside the let-body we represent the source with the “src” identifier:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;With let&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;source = GetNums(10);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;res = source.Let(src =&amp;gt;
                &lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;src
                &lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;src
                &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + y);

    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;i &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
        ;
}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Now things look much better:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_9.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_9.png" width="433" height="34" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Obviously the computed results will be the same (not visualized here – we’re just showing the side-effects), but we got rid of the excessive side-effect replication. This said, consuming a Let’s output multiple times doesn’t prevent the source from being consulted more than once: only &lt;em&gt;inside&lt;/em&gt; the Let-block, consumers are shielded from side-effect duplication, but &lt;em&gt;outside&lt;/em&gt;, consumers of the Let-block itself don’t get protection:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&amp;#160;&lt;/p&gt;

  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;With let (twice)&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;source = GetNums(10);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;res = source.Let(src =&amp;gt;
    {
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Let!&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;return from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;src
               &lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;src
               &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + y;
    });

    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;i &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
        ;

    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;i &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
        ;
}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;We enumerate twice over the output of Let, hence we see the side-effects twice (and not 22 times as would be the case if we left Let out of the picture altogether):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_10.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_10.png" width="432" height="73" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;However, nothing prevents us from putting a Let over the Let we already have: let’s eliminate the common subexpression &lt;em&gt;res&lt;/em&gt; in both foreach-statements as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;With let (nested)&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;source = GetNums(10);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;res = source.Let(src =&amp;gt;
        {
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Let!&amp;quot;&lt;/span&gt;);
            &lt;span style="color:blue;"&gt;return from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;src
                   &lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;src
                   &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + y;
        });

    res.Let(src =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;i &lt;span style="color:blue;"&gt;in &lt;/span&gt;src)
            ;

        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;i &lt;span style="color:blue;"&gt;in &lt;/span&gt;src)
            ;

        &lt;span style="color:blue;"&gt;return new int&lt;/span&gt;[] { }; &lt;span style="color:green;"&gt;// doesn&amp;#39;t matter, we want an &amp;quot;imperative let&amp;quot;
    &lt;/span&gt;}).ToArray(); &lt;span style="color:green;"&gt;// forces evaluation
&lt;/span&gt;}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Sure enough, we’re back to the minimum amount of side-effects:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_11.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_11.png" width="432" height="45" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And finally, some direct uses of Memoize, assuming the following exposition on IEnumerable&amp;lt;T&amp;gt; is present:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Memoize&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemoizeEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;(source);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we use our lottery iterator as a source and show that the sequences are not equal without memoization as they are enumerated multiple times and hence different random numbers are picked for two uses of the source:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Without memoize&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;src = Lotto();
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(src.SequenceEqual(src));
}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();

&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;With memoize&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:blue;"&gt;using &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;src = Lotto().Memoize())
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(src.SequenceEqual(src));
}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;With the Memoization in use, obviously the two sequences ought to be the same all the time:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_12.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_12.png" width="131" height="199" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;One more thing to illustrate is the use of infinite streams by means of a Repeat operator:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Repeat&amp;lt;T&amp;gt;(T value)
{
    &lt;span style="color:blue;"&gt;while &lt;/span&gt;(&lt;span style="color:blue;"&gt;true&lt;/span&gt;)
        &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;value;
}

&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Repeat&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;while &lt;/span&gt;(&lt;span style="color:blue;"&gt;true&lt;/span&gt;)
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;item &lt;span style="color:blue;"&gt;in &lt;/span&gt;source)
            &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;item;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;It should be clear that the use of eagerly evaluated operators like ToArray and ToList won’t work as a side-effect-avoiding technique in such a setting. However, with Memoize one can eliminate side-effects without getting stuck:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Memoize prevents _|_ out&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:blue;"&gt;using &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;mem = &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Repeat(1).Memoize())
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(mem.Take(10).Count());
}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();

&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;ToList may _|_ out&amp;quot;&lt;/span&gt;);
{
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Repeat(1).ToList().Take(10).Count());
}
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The samples above are not of interest for side-effects (though one can easily come up with samples), but rather for their infinite character. Use of ToList will exhaust the managed heap quickly, while Memoize just fills memory for the objects that are ever requested downstream (in the case above “Take 10”).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_13.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TamingYourSequencesSideEffectsThroug.Let_12E8F/image_thumb_13.png" width="341" height="80" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Wonder about the _|_ notation? This is the “&lt;a href="http://en.wikipedia.org/wiki/Bottom_type"&gt;bottom type&lt;/a&gt;”, one way to type non-termination. “Entre parentheses”, we don’t have such a thing in the world of .NET, which is a pity. For example, if you have an exception throwing helper method:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static void &lt;/font&gt;ThrowAlways() 

      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;MyException&lt;/font&gt;(&lt;font color="#008000"&gt;/* localization fluff */&lt;/font&gt;); 

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and you call the above from a function to signal an exception:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static int &lt;/font&gt;Bar() 

      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(cond) 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; … 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;else&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThrowAlways(); 

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;the compiler will complain that “not all code paths return a value”. Void is not the same as bottom, flow analysis cannot know the method won’t every return. With a bottom type, e.g. using keyword “never” (or more juicy ones like “blackhole”, “getstuck”, “goodbye”, “farewell”), one could say:&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static never &lt;/font&gt;ThrowAlways() 

    &lt;br /&gt;{ 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;MyException&lt;/font&gt;(&lt;font color="#008000"&gt;/* localization fluff */&lt;/font&gt;); 

    &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;Now the compiler would check statically that ThrowAlways can never reach its end (either by throwing an exception, looping infinitely or calling other “never”-returning methods). At the call-site, the compiler would be happy with Bar’s definition as well since it knows ThrowAlways never returns, hence there’s no need to be worried about not having a return value for the enclosing method. And of course, if we also had union types, we could (or maybe should, depending on how pesky the compiler would be made) warn the user that Bar may never return:&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static &lt;font color="#000000"&gt;(&lt;/font&gt;never &lt;font color="#000000"&gt;| &lt;/font&gt;int&lt;font color="#000000"&gt;)&lt;/font&gt; &lt;/font&gt;Bar() 

    &lt;br /&gt;{ 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(cond) 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; … 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;else&lt;/font&gt; 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThrowAlways(); 

    &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;But all of this deserves its own discussion another time.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;If you don’t want to tame your side-effects, you should at least have good notions about where they happen and how they may get replicated by mixing lazy and eager evaluation in languages like C#. Enumerable.Let shows one approach to taming side-effects in the context of LINQ queries with side-effecting computed sequences (iterators).&lt;/p&gt;

&lt;p&gt;If you can’t get enough of this stuff, check out Erik Meijer’s talks on &lt;a href="http://www.bing.com/videos/search?q=Fundamentalist+Functional+Programming&amp;amp;FORM=BVFD#"&gt;Fundamentalist Functional Programming&lt;/a&gt;. Credits where credits are due, the Enumerable.Let exercise shown in here presents the &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;dual&lt;/a&gt; of the IObservable’s Let operator (from the &lt;a href="http://www.bing.com/search?q=reactive+linq&amp;amp;form=QBLH&amp;amp;qs=n"&gt;Reactive LINQ framework&lt;/a&gt; Erik and his team have been working on lately), which I’ll talk about another time.&lt;/p&gt;

&lt;p&gt;Left as a challenge for the reader: can you think of a way to port let’s brother “&lt;a href="http://www.bing.com/search?q=letrec+let&amp;amp;form=QBRE&amp;amp;qs=n"&gt;letrec&lt;/a&gt;” to the world of IEnumerable&amp;lt;T&amp;gt; as well? &lt;em&gt;Let &lt;/em&gt;completeness be your source of inspiration :-).&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14791" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Functional+programming/default.aspx">Functional programming</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Type+theory/default.aspx">Type theory</category></item><item><title>ExceLINQ – Not Your Typical LINQ Provider</title><link>http://community.bartdesmet.net/blogs/bart/archive/2009/03/28/excelinq-not-your-typical-linq-provider.aspx</link><pubDate>Sun, 29 Mar 2009 00:16:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14336</guid><dc:creator>bart</dc:creator><slash:comments>109</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14336</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2009/03/28/excelinq-not-your-typical-linq-provider.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;On &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/02/22/upcoming-trips-techdays-finland-belgium-and-more.aspx"&gt;my last trip&lt;/a&gt; I had the opportunity to talk on the subject of LINQ once more. Geeky as we are, this time’s session title was “LINQ in breadth”, an orthogonal view on LINQ compared to my last year’s LINQ in depth talk.&lt;/p&gt;  &lt;p&gt;But what makes LINQ have a certain breadth? The simple answer: its spectrum of possible LINQ “provider” implementations. Far too often people think LINQ is only extensible by means of the IQueryable&amp;lt;T&amp;gt; interface which makes you opt-in to every imaginable query operator. That’s one useful side of the LINQ spectrum (albeit most of the time an overkill approach). The totally opposite end of the spectrum is ironically IEnumerable&amp;lt;T&amp;gt;. I say ironically because theoretically both interfaces are identical (I should really go into monads once more, but let’s suppress that urge). It’s just that making something LINQable is trivial if one can expose the data as an IEnumerable&amp;lt;T&amp;gt; because from that point on one can fall back to LINQ to Objects (and that’s precisely what LINQ to XML does).&lt;/p&gt;  &lt;p&gt;The rest of the breadth comes from all intermediate implementations that are possible. I’ve mentioned before that, from a language perspective, LINQ is a tiny syntactical layer on top of the rest of the language. To be convinced about that, look at my &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/30/c-3-0-query-expression-translation-cheat-sheet.aspx"&gt;C# 3.0 Query Expression Translation Cheat Sheet&lt;/a&gt;. All you’re seeing there is some kind of fixpoint algorithm that gradually compiles away the C# 3.0 language’s knowledge of query comprehension syntax till nothing but methods and operands remain.&lt;/p&gt;  &lt;p&gt;All of this means we can party along on the syntactical sugar that LINQ provides us, as shown in my &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/09/14/who-ever-said-linq-predicates-need-to-be-boolean-valued.aspx"&gt;“Who ever said LINQ predicates need to be Boolean-valued?” post&lt;/a&gt;. It turns out I’ve talked about this &lt;strong&gt;spectrum theory&lt;/strong&gt; over there too. All of this can be used for samples that are only of technical value, like LINQ to Simpsons (see below), but also to create useful stuff.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb.png" width="440" height="209" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;(Exercise for the reader: what’s the type of x in the fragment above?)&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The genesis of ExceLINQ&lt;/h1&gt;  &lt;p&gt;So, while preparing for my demos, I was thinking about potential samples of non-obvious but nevertheless useful LINQ implementations. Rather by accident I came up with bridging Excel to LINQ. Maybe a short story on how that idea came along. One evening (night according to the post’s publication time) I was writing up a blog entry on &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/02/14/the-m-programming-language-part-0-intellipad-mrepl-vs2008-project-support-and-excel-integration.aspx"&gt;“The M Programming Language – Part 0 – Intellipad, MrEPL, VS2008 project support and Excel integration”&lt;/a&gt; (more posts on &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/tags/M/default.aspx"&gt;that topic&lt;/a&gt; to follow soon). As I’m not the kind of guy that spontaneously opens Excel – which &lt;em&gt;doesn’t&lt;/em&gt; mean I don’t like the product, I just don’t have a job that requires overdoses of spreadsheet interaction on a day-to-day basis – I took the opportunity to browse a bit more through the product in its current form. The last screenshot is where the fascination kicked in:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;img src="http://www.bartdesmet.info/images_wlw/TheMProgrammingLanguagePart0IntelliPadMr_1837/image_17.png" alt="" /&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Clicking the little arrows on the column headers reveals a whole new world (I admit I was exposed to it in a distant past, but it was a pleasant deja-vu as you can tell, otherwise this post wouldn’t exist):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_3.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_3.png" width="402" height="405" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Query operators, anyone? As I already had a C# project open to prepare C# 4.0 demos on improved COM interop (posts on &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx"&gt;that&lt;/a&gt; to follow too), I decided to explore the Excel automation APIs a bit more. Here are a few of the interesting methods I came across:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.autofilter(VS.80).aspx"&gt;Range.AutoFilter&lt;/a&gt; – filters based on one or more predicates &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/bb178517.aspx"&gt;SortFields.Add&lt;/a&gt; – and much more plumbing to do sorting &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._application.union(VS.80).aspx"&gt;_Application.Union&lt;/a&gt; – usable for simple column projections; a COM interop beauty with no less than 30 parameters, 28 of which are optional (luckily C# 4.0 will help out here – yes, you can say “finally” if you want) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Great, lots of stuff that’s applicable to querying. But let’s not settle for the obvious: creating a LINQ binding that results in yet another IEnumerable&amp;lt;T&amp;gt; where T is an entity type representing a set of strongly-typed columns (with an ExcelMetal.exe export tool, sounds familiar doesn’t it?). To illustrate the flexibility of LINQ I wanted the query to return something non-obvious. What about an Excel chart? In preparing my C# 4.0 talk I’d been exposed to Office interop code to create a chart in Excel, so that was certainly doable too.&lt;/p&gt;  &lt;p&gt;Ah beautiful – it was the first time I didn’t curse myself for going on a &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/02/22/upcoming-trips-techdays-finland-belgium-and-more.aspx"&gt;speaking tour with 7 distinct talks&lt;/a&gt;. After all my M talk led me to dive into Excel, link it to C# 4.0 COM interop to end up with something applicable for my LINQ talk. And obviously I added PowerShell to the ingredients by showing off &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/06/07/linq-through-powershell.aspx"&gt;LINQ through PowerShell&lt;/a&gt; during that talk too :-).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The mission statement for ExceLINQ&lt;/h1&gt;  &lt;p&gt;Another great distinction between developers and managers: the latter need to open up Word to come up with a mission statement, while the former group opens up their favorite IDE to cook up a prototype. So in the true sense of “say it with code”, here’s what I want to accomplish:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;src = &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#008080"&gt;ExcelSource&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Proc&lt;/font&gt;&amp;gt;(_file))         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;proc &lt;font color="#0000ff"&gt;in &lt;/font&gt;src         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;where &lt;/font&gt;proc.WorkingSet &amp;gt; 20 * 1024 * 1024         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;where &lt;/font&gt;proc.Name.StartsWith(&lt;font color="#800000"&gt;&amp;quot;D&amp;quot;&lt;/font&gt;)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;orderby &lt;/font&gt;proc.WorkingSet         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select new &lt;/font&gt;&lt;font color="#008080"&gt;Column&lt;/font&gt;[] { proc.Name, proc.WorkingSet };         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; pictureBox1.Image = res.ToChart(&lt;font color="#008080"&gt;XlChartType&lt;/font&gt;.xlColumnClustered);         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Or more graphically, a press of the button results in a chart being rendered:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_4.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_4.png" width="244" height="180" /&gt;&lt;/a&gt; &lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_5.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_5.png" width="244" height="180" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We could go even further and allow any IEnumerable&amp;lt;T&amp;gt; to be imported into Excel transparently in order to create a chart, but in the sample above I’m simply using an existing Excel file (which I populated manually using Excel interop code). But hey, it’s a proof-of-concept.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The construction of ExceLINQ&lt;/h1&gt;  &lt;p&gt;There’s a magical touch to ExceLINQ. The query shown above does look like a regular LINQ query, yet there’s a bunch of stuff going on even in just declaring the query. What if I told you that the &amp;gt; operator in the first where clause is not the one you’d expect? And what if I told you that none of the query operators you’re seeing is defined in the same spot (like Enumerable or Queryable)? Indeed, everything is custom in ExceLINQ: a la carte cuisine, no microwave food.&lt;/p&gt;  &lt;p&gt;Regular readers of this blog will be bored by what follows in this paragraph (hopefully not by the things coming in the subsequent ones), but the query fragment above translates into:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;src.Where(proc =&amp;gt; proc.WorkingSet &amp;gt; 20 * 1024 * 1024).Where(proc =&amp;gt; proc.Name.StartsWith(“D”)).OrderBy(proc =&amp;gt; proc.WorkingSet).Select(proc =&amp;gt; new Column[] { proc.Name, proc.WorkingSet })&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I kept everything on one line deliberately to emphasize the fluent interface LINQ is. At this point there’s no query comprehension syntax left and the compiler falls back to the well-known rules for method overload resolution, processing from the left to the right (duh). In other words: given src which is of type ExcelSource&amp;lt;Proc&amp;gt;, can we find a method called Where that takes one argument with type …:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;src.&lt;strong&gt;&lt;u&gt;Where&lt;/u&gt;&lt;/strong&gt;(proc =&amp;gt; proc.WorkingSet &amp;gt; 20 * 1024 * 1024)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Right, but what’s the type of the argument? We can only tell once we know what the type of proc is, so we can compute the type of the lambda body. One thing’s sure: the “shape” of the argument is required to be a Func&amp;lt;A, B&amp;gt;, a function from some type to another type (type theorists will see a relationship to the concept of &lt;a href="http://en.wikipedia.org/wiki/Kind_(type_theory)"&gt;kinds&lt;/a&gt;).&lt;/p&gt;  &lt;p&gt;All we need to see from this discussion is that we can provide our own Where method (possibly an instance method, or an extension method but there’s no reason to choose for the latter option in this case) and as long as it has the right shape of signature, the compiler will be happy. Let’s reveal its signature now:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Query&lt;/font&gt;&amp;lt;T&amp;gt; Where(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#008080"&gt;Filter&lt;/font&gt;&amp;gt; filter)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We see the generic parameter T comes from the surrounding type, ExcelSource&amp;lt;T&amp;gt;. Obviously T is meant to be substituted for an entity type, a strongly-typed representation of the columns in the worksheet. This mapping is nothing fancy:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="courier New"&gt;[&lt;font color="#008080"&gt;Sheet&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;Sheet1&amp;quot;&lt;/font&gt;)]         &lt;br /&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Proc&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [&lt;font color="#008080"&gt;Column&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;A&amp;quot;&lt;/font&gt;)]         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;StringColumn &lt;/font&gt;Name { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="courier New"&gt;&amp;#160;&amp;#160;&amp;#160; [&lt;font color="#008080"&gt;Column&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;B&amp;quot;&lt;/font&gt;)]         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;IntColumn &lt;/font&gt;WorkingSet { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Ignore the custom attributes for now, those are true details required for the interop plumbing to correlate entity types to sheets and properties to columns in that sheet. Trivial stuff to define and to use. What’s more important is the typing we’re looking at. Name is not a string, it’s a StringColumn. Similarly WorkingSet isn’t an int, but rather it’s an IntColumn.&lt;/p&gt;  &lt;p&gt;So, looking back at our Where method, “proc” ought to be an instance of Proc, hence the lambda body should be the type of:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;proc.WorkingSet &amp;gt; 20 * 1024 * 1024&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We know WorkingSet is of type IntColumn, so the &amp;gt; comparison operator can only come from an operator overload defined on that type:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;IntColumn &lt;/font&gt;: &lt;font color="#008080"&gt;Column&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;Filter &lt;/font&gt;&lt;font color="#0000ff"&gt;operator &lt;/font&gt;&amp;gt;(&lt;font color="#008080"&gt;IntColumn &lt;/font&gt;column, &lt;font color="#0000ff"&gt;int &lt;/font&gt;value)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return new &lt;/font&gt;&lt;font color="#008080"&gt;Filter&lt;/font&gt;(column, &lt;font color="#008080"&gt;FilterType&lt;/font&gt;.GreaterThan, value);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; …         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As you can see, the return type of this operator is Filter, so the entire lambda expression is assignable to the Func&amp;lt;T, Filter&amp;gt; and the call to Where is working out fine:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;src.&lt;strong&gt;&lt;u&gt;Where&lt;/u&gt;&lt;/strong&gt;(proc =&amp;gt; proc.WorkingSet &amp;gt; 20 * 1024 * 1024)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;returns a Query&amp;lt;T&amp;gt; instance as seen from the Where method signature. Next in the chain of method calls, we find another call to Where:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;src.Where(proc =&amp;gt; proc.WorkingSet &amp;gt; 20 * 1024 * 1024).&lt;strong&gt;&lt;u&gt;Where&lt;/u&gt;&lt;/strong&gt;(proc =&amp;gt; proc.Name.StartsWith(“D”))&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So Query&amp;lt;T&amp;gt; should again have a Where method defined, an indeed it does:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Query&lt;/font&gt;&amp;lt;T&amp;gt; Where(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#008080"&gt;Filter&lt;/font&gt;&amp;gt; filter)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now proc.Name is of type StringColumn, so the StartsWith method should be the guy returning the Filter instance required to make the Where method happy:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;StringColumn &lt;/font&gt;: &lt;font color="#008080"&gt;Column&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Filter &lt;/font&gt;StartsWith(&lt;font color="#0000ff"&gt;string &lt;/font&gt;value)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return new &lt;/font&gt;&lt;font color="#008080"&gt;Filter&lt;/font&gt;(&lt;font color="#0000ff"&gt;this&lt;/font&gt;, &lt;font color="#008080"&gt;FilterType&lt;/font&gt;.StartsWith, value);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; …         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You get the idea. In a very similar way the OrderBy method is defined on Query&amp;lt;T&amp;gt;. This time it doesn’t take in a lambda producing a Filter (as ordering is not filtering, right?), but rather a lambda that produces a Column. After all the function required to carry out an ordering is a so-called key extractor (and we don’t bother about things like composite keys here):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Query&lt;/font&gt;&amp;lt;T&amp;gt; OrderBy(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#008080"&gt;Column&lt;/font&gt;&amp;gt; column)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As both properties on Proc are typed to be *Column, each of which derives from the Column base class, the OrderBy call succeeds:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;src.Where(proc =&amp;gt; proc.WorkingSet &amp;gt; 20 * 1024 * 1024).Where(proc =&amp;gt; proc.Name.StartsWith(“D”)).&lt;strong&gt;&lt;u&gt;OrderBy&lt;/u&gt;&lt;/strong&gt;(proc =&amp;gt; proc.WorkingSet)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The final call is a Select call, which is typed as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Result&lt;/font&gt;&amp;lt;T&amp;gt; Select(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#008080"&gt;Column&lt;/font&gt;[]&amp;gt; project)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice two things here:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The return type of the projection lambda is not generic (as in other LINQ implementations, where the projection function would be a Func&amp;lt;T, R&amp;gt; where R can be anything, e.g. an anonymous type). This way we make sure the user just returns a set of columns with no fancy decoration over it (like new { Bar = x.Foo } which results in an anonymous type). &lt;/li&gt;    &lt;li&gt;The return type of the whole Select query operator is of type Result&amp;lt;T&amp;gt;, no longer Query&amp;lt;T&amp;gt;. This means we can’t continue our query beyond the Select call (assuming we don’t provide methods like Where, OrderBy, Select on Result&amp;lt;T&amp;gt;, which we don’t). By doing this, we can rest assured the user doesn’t “keep going on” and our query is terminated properly. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The last point is quite important. In fact we’ve created a state machine of types. Starting from an ExcelSource&amp;lt;T&amp;gt;, we transitioned into Query&amp;lt;T&amp;gt; to end up with Result&amp;lt;T&amp;gt;. You could go much further in controlling the order of operators and the number of operator calls that are allowed (e.g. a maximum of two Where calls) but creating much more types:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_6.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_6.png" width="589" height="232" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Finally we have a Result&amp;lt;T&amp;gt;, which has a method to turn the result into a chart:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Image &lt;/font&gt;ToChart(&lt;font color="#008080"&gt;XlChartType &lt;/font&gt;chartType)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where Image is the built-in System.Drawing.Image class from the .NET Framework.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The plumbing of ExceLINQ&lt;/h1&gt;  &lt;p&gt;We’re done with the conceptual part of our mission. The user can write queries that result in calls being made to our own methods on types like Query&amp;lt;T&amp;gt;. Even more, we gained control over the lambda expressions that are passed to those query operators too. So we have all the information about the query the user intended to write, meaning we can turn it into execution.&lt;/p&gt;  &lt;p&gt;That’s where the plumbing part comes in. The implementation of our query operator methods needs to collect all the information about the query. Once we have aggregated all of this knowledge into a Result&amp;lt;T&amp;gt; object, we need to turn it into instructions that Excel understands. And finally, we ask Excel to generate the graph upon calling Result&amp;lt;T&amp;gt;.ToChart, producing an Image instance somehow. All of this is quite irrelevant to the LINQ topic in this post.&lt;/p&gt;  &lt;p&gt;I’ll omit all of the COM interop magic as it doesn’t contribute much to the core idea, but there’s one thing I should dive into a bit more here. We’ve seen that purely based on the type information available through ExcelSource&amp;lt;T&amp;gt;, more particularly because of the T part in there, we can write strongly typed queries over some entity type like the one below:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="courier New"&gt;[&lt;font color="#008080"&gt;Sheet&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;Sheet1&amp;quot;&lt;/font&gt;)]         &lt;br /&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Proc&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [&lt;font color="#008080"&gt;Column&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;A&amp;quot;&lt;/font&gt;)]         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;StringColumn &lt;/font&gt;Name { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="courier New"&gt;&amp;#160;&amp;#160;&amp;#160; [&lt;font color="#008080"&gt;Column&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;B&amp;quot;&lt;/font&gt;)]         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;IntColumn &lt;/font&gt;WorkingSet { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We’ve also seen that we defined operators like Where based on such an entity type, e.g. taking in a Func&amp;lt;T, Filter&amp;gt; where T is substituted for the particular entity type we’re dealing with:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;where &lt;/font&gt;proc.WorkingSet &amp;gt; 20 * 1024 * 1024&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The reason we did that is to be able to call the (in this case predicate-valued) delegate to get the corresponding filter object (i.e. the runtime representation of the &amp;gt; condition applied in the predicate) without further runtime hoops. Those hoops would come from the IQueryable style of query provider implementation where the predicate would not be a Func&amp;lt;T, Filter&amp;gt; but an Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt;, hence the user could write all sorts of expressions that ultimately produce a Boolean value, and although the compiler would be fine with that, we might give up at runtime because the generated expression tree is too complex (e.g. when the user wrote something like “where CallGreenManOnMars(proc).Replied(“Okay”)”, which doesn’t make sense but type-checks fine). In some sense, we pushed down the Expression&amp;lt;…&amp;gt; part into the function signature to constrain the lambda body to something of type Filter, which is our mini (domain-specific) expression tree.&lt;/p&gt;  &lt;p&gt;There’s something missing though: in order to get the result of the predicate delegate, we need to feed it an &lt;em&gt;instance&lt;/em&gt; of the entity type T, in this case a Proc instance. Moreover, we need to make sure all properties are properly instantiated because we’re about to call into them during the execution of the lambda body, e.g. by doing “proc.WorkingSet”.&lt;/p&gt;  &lt;p&gt;The way we accomplish this is by new’ing up the entity type at runtime and filling in the properties dynamically:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;internal static&lt;/font&gt; T CreateInstance&amp;lt;T&amp;gt;()         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; T res = &lt;font color="#008080"&gt;Activator&lt;/font&gt;.CreateInstance&amp;lt;T&amp;gt;(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;mappings = &lt;font color="#0000ff"&gt;from &lt;/font&gt;prop &lt;font color="#0000ff"&gt;in typeof&lt;/font&gt;(T).GetProperties()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select new &lt;/font&gt;{ Property = prop, Attribute = prop.GetCustomAttributes(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#008080"&gt;ColumnAttribute&lt;/font&gt;), &lt;font color="#0000ff"&gt;false&lt;/font&gt;).Cast&amp;lt;&lt;font color="#008080"&gt;ColumnAttribute&lt;/font&gt;&amp;gt;().Single() }; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;columns = mappings.OrderBy(column =&amp;gt; column.Attribute.Column);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;first = columns.First().Attribute.Column[0]; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;col &lt;font color="#0000ff"&gt;in &lt;/font&gt;columns)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;object &lt;/font&gt;colObj = col.Property.PropertyType.GetConstructor(&lt;font color="#008080"&gt;BindingFlags&lt;/font&gt;.Instance | &lt;font color="#008080"&gt;BindingFlags&lt;/font&gt;.NonPublic, &lt;font color="#0000ff"&gt;null&lt;/font&gt;, &lt;font color="#0000ff"&gt;new &lt;/font&gt;[] { &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;), &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;) }, &lt;font color="#0000ff"&gt;null&lt;/font&gt;)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[] { col.Attribute.Column, (&lt;font color="#0000ff"&gt;int&lt;/font&gt;)(1 + col.Attribute.Column[0] - first) });         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; col.Property.SetValue(res, colObj, &lt;font color="#0000ff"&gt;null&lt;/font&gt;);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;res;         &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Let’s step through this a bit. On the first line we create an instance of T, nothing fancy (an alternative would have been to have a generic parameter constraint for a default constructor, it just turned out this way for no particularly good reason and, hey, this is just a sample). Next we use LINQ to Objects (don’t you love it?) to get all the properties and their ColumnAttribute mapping. I’m using the Single operator here, so foreign properties (which don’t have a mapping attribute) will cause our CreateInstance method to fail. I could be more polite and ignore those properties or define my own exception type here (which I should really have done) but you get the idea.&lt;/p&gt;  &lt;p&gt;Finally, the loop going over the columns is required to instantiate each individual property. Again, we’re a bit lazy here and expect the properties to be of a Column-derived type we know about, as we assume a two-parameter private constructor is available to new that up. To make this code production quality you’d obviously go for more thorough checking code with proper exception types being used to signal failures. The bit of tricky code here is to order the columns, so that we can determine the column index in the spreadsheet, required for other COM plumbing code where we select Excel ranges. This is just an implementation detail and could be eliminated with some more careful study of the Office automation libraries (but I’m not an Office programming expert at all). Here’s a sample column type with the constructor used:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Column&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;protected &lt;/font&gt;Column(&lt;font color="#0000ff"&gt;string &lt;/font&gt;name, &lt;font color="#0000ff"&gt;int &lt;/font&gt;index)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Name = name;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Index = index;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public string &lt;/font&gt;Name { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public int &lt;/font&gt;Index { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; }         &lt;br /&gt;}         &lt;br /&gt;&lt;/font&gt;&lt;font color="#0000ff"&gt;       &lt;br /&gt;&lt;font face="Courier New"&gt;class &lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;StringColumn &lt;/font&gt;: &lt;font color="#008080"&gt;Column&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;internal &lt;/font&gt;StringColumn(&lt;font color="#0000ff"&gt;string &lt;/font&gt;name, &lt;font color="#0000ff"&gt;int &lt;/font&gt;index)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; : &lt;font color="#0000ff"&gt;base&lt;/font&gt;(name, index)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; …         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The state of ExceLINQ&lt;/h1&gt;  &lt;p&gt;As mentioned repeatedly during my post write-up, ExceLINQ is more of a conceptual rapidly-prototyped piece of demo code, so there’s lots of room for improvement left to be made:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;General code clean-up, proper error handling and use of C# 4.0 dynamic to reduce COM interop plumbing. &lt;/li&gt;    &lt;li&gt;Query&amp;lt;T&amp;gt; mutates its own state on every query operator call; it would be better to return new instances on every call as queries might act as the base for other queries (a common pattern). &lt;/li&gt;    &lt;li&gt;A better design would be to go for the “type state machine approach” as outlined in this post, to restrict the order and multiplicity of query operators. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Anyway, if you’re curious to see how all of this works, I’ve uploaded the prototype &lt;a href="http://www.bartdesmet.net/download/ExceLINQ.zip"&gt;over here&lt;/a&gt;. &lt;font color="#ff0000"&gt;Usual warnings about sample code apply.&lt;/font&gt; Below is a nice scenery of ExceLINQ stepping through:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_7.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_7.png" width="582" height="144" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now pressing F10 applies the first Where clause, causing the filter to be applied in Excel instantaneously.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_8.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_8.png" width="582" height="144" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice the filtering icon in the first row now. This live filtering makes ExceLINQ an ideal visualization of query execution, which was a big appealing factor to use it for my “LINQ in Breadth” demo. Next we apply ordering:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_9.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_9.png" width="563" height="206" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;and again, continuing execution causes immediate filtering application (notice the little sorting arrow in cell B1):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_10.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/ExceLINQNotYourTypicalLINQProvider_1097F/image_thumb_10.png" width="563" height="208" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14336" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>Help! Drowning in Expression Trees, What Now?</title><link>http://community.bartdesmet.net/blogs/bart/archive/2009/02/12/help-drowning-in-expression-trees-what-now.aspx</link><pubDate>Thu, 12 Feb 2009 11:50:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14200</guid><dc:creator>bart</dc:creator><slash:comments>36</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14200</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2009/02/12/help-drowning-in-expression-trees-what-now.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;Once more I found myself in LINQ providers land recently for a project yet unannounced. Given the relative poverty of the query language we’re targeting in that particular provider, a very common question came up: what about complex expressions in predicates? Let me give you an example:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;products &lt;font color="#0000ff"&gt;where &lt;/font&gt;p.Price &amp;gt; 100 &lt;font color="#0000ff"&gt;select &lt;/font&gt;p&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;is a pretty innocent query, right? But what about:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;products &lt;font color="#0000ff"&gt;where &lt;/font&gt;EnterUnknownTerritory(p.Price * Math.PI / 4) == 26 &lt;font color="#0000ff"&gt;select &lt;/font&gt;p&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;That’s the totally opposite side of the spectrum, where we can’t translate the query anymore because the “EnterUnknownTerritory” method is definitely not known in the target language. So, take a look at something “in the center”, not quite trivial but by no means impossible:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;products &lt;font color="#0000ff"&gt;where &lt;/font&gt;p.Price &amp;gt; minPrice &lt;font color="#0000ff"&gt;select &lt;/font&gt;p&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where minPrice is a variable. You might say this is as innocent as the original query, but in fact quite some stuff is going on here. Remember that LINQ queries are composed of chains of method calls each of which represent a query operator. In the sample above that boils down to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;products.Where(p =&amp;gt; p.Price &amp;gt; minPrice)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The argument to the Where method is a lambda expression that captures an outer variable, so you end up with a closure and minPrice becomes a field access on the closure class. Here’s an illustration of this behavior:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image_thumb.png" width="471" height="53" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So, MemberExpressions are lurking around every corner, sometime a little unexpectedly. Another sample of user-induced complication of expression trees (most likely well-intentioned anyway) is the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;products &lt;font color="#0000ff"&gt;where &lt;/font&gt;p.Price &amp;gt; 100 &amp;amp;&amp;amp; someThingLocal.Equals(alsoLocal) &lt;font color="#0000ff"&gt;select &lt;/font&gt;p&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where whole parts of the expression tree can be evaluated locally, meaning the above query can be simplified by applying the rules of Boolean logic after partial evaluation of the local portions.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Approach #1 – Foreign nodes&lt;/h1&gt;  &lt;p&gt;So, how to tackle this “issue”? As part of any expression tree translator (whether it’s LINQ or something else) you’ll turn the source tree into some target tree, resembling the abstract syntax of the target domain. Typically this is carried out by some kind of expression tree visitor that recursively “visits” the tree, translating nodes and putting them together. For example, you might recognize a BinaryExpression with NodeType set to ExpressionType.AndAlso and turn it into an AndPredicate:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;BinaryPredicate &lt;/font&gt;VisitAndAlso(&lt;font color="#008080"&gt;BinaryExpression &lt;/font&gt;andAlso)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;&lt;font color="#008080"&gt;Predicate&lt;/font&gt;.AndAlso(Visit(andAlso.Left), Visit(andAlso.Right));      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Here Visit is the top-level method that can take in an arbitrary (System.Linq-based) expression, and we’re turning everything into Predicate objects, our destination universe. The top-level method will look much like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt; &lt;font color="#008080"&gt;Predicate &lt;/font&gt;Visit(&lt;font color="#008080"&gt;Expression &lt;/font&gt;ex)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;switch &lt;/font&gt;(ex.NodeType)      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case &lt;/font&gt;&lt;font color="#008080"&gt;ExpressionType&lt;/font&gt;.AndAlso:      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;VisitAndAlso((&lt;font color="#008080"&gt;BinaryExpression&lt;/font&gt;)ex);      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; …      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Obviously you’ll add much more cases to the Visit method, and likely you’ll merge implementations for various binary operations that share a common implementation (recurse, construct, return). That said, at some point you’ll end up with things you don’t know about. Let’s use method calls as a sample. Maybe a method call itself is still of interest (in a sense it can be turned into a target-side equivalent), like:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;p.Name.Equals(“Chai”)&lt;/li&gt;    &lt;li&gt;String.Equals(p.Name, “Chai”)&lt;/li&gt;    &lt;li&gt;p.Price.CompareTo(100)&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;but at some level, inevitably, you’ll end up with lots of unknowns, like (assuming the methods invoked below don’t have a target-side equivalent):&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;EnterUnknownTerritory(p.Price * Math.PI / 4)&lt;/li&gt;    &lt;li&gt;p.Name.Normalize()&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Outside the domain of method calls, similar unknowns can exist. Maybe the target language can’t cope with a Boolean Not, or with a simple numerical addition. Either way, you’re drowning in expression trees at that point, and the subtree you’re stuck at becomes an “unknown” to you.&lt;/p&gt;  &lt;p&gt;Now two things can happen: either the unknown expression tree node has a dependency on a target-side thing (brought in scope through abstraction, i.e. lambda parameters), or it’s completely defined source-side (in the C#/VB local execution domain). The samples above fall under the former category because of the occurrence of “p” in the expression subtree.&lt;/p&gt;  &lt;p&gt;During the first visit over the tree, you could (and maybe should) decide not to investigate the unknown territory yet, and invent some pseudo-node in the target domain AST that represents something “Foreign”:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;return &lt;/font&gt;&lt;font color="#008080"&gt;Predicate&lt;/font&gt;.Foreign(ex);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;On a subsequent phase in the compiler, you’d decide whether or not you can evaluate the expression (some kind of partial evaluation of the entire expression) locally. If so, it gets substituted by a constant node (containing the result of source-side evaluation); if not, an exception occurs (like NotSupportedException). How to figure out whether you can do local evaluation or not? Detect whether or not foreign expression contains (again recursively by some visitor) references to the lambda parameter representing the input to the predicate clause (i.e. representing the target-side entity, e.g. a database row or entity).&lt;/p&gt;  &lt;p&gt;The evaluation itself can be done in two ways:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A complete expression tree interpreter: quite a bit of work.&lt;/li&gt;    &lt;li&gt;Some trick, like wrapping the remaining expression in a lambda expression, using the Compile method on it and invoke the resulting delegate, like this:     &lt;br /&gt;      &lt;br /&gt;&lt;font color="#0000ff"&gt;object &lt;/font&gt;result = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda(foreignEx).Compile().DynamicInvoke();      &lt;br /&gt;      &lt;br /&gt;Note this could actually be used to figure out the foreign expression is lambda parameter free, because an InvalidOperationException will result from the Compile method if this is not the case. (Question for the reader: is the premise of requiring a foreign expression to be completely lambda-parameter-free valid?)&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Approach #2 – Avoid the problem altogether&lt;/h1&gt;  &lt;p&gt;How’s that for a solution? If the target domain is sufficiently poor with a relatively little number of operators and such, you could try to avoid general expression trees altogether. But how? Let’s stick with query predicates (the where clause body) for our discussion to simplify matters a bit. Remember my post titled &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/09/14/who-ever-said-linq-predicates-need-to-be-boolean-valued.aspx"&gt;Who ever said LINQ predicates need to be Boolean-valued?&lt;/a&gt; from last year? That’s precisely the thing we’re going to leverage here. Instead of assigning the predicate lambda to an Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt;, let’s “assign it” to a Func&amp;lt;T, Predicate&amp;gt;. Sounds awkward? Not really, if the way to build up the Predicate instance (which is already in a pretty good shape to be turned into the final destination language, as it reflects the AST of the target language quite accurately already) is user-friendly enough.&lt;/p&gt;  &lt;p&gt;What do I mean with that? Well, you most certainly don’t want the user to write the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;products &lt;font color="#0000ff"&gt;where &lt;/font&gt;&lt;font color="#008080"&gt;Predicate&lt;/font&gt;.AndAlso(&lt;font color="#008080"&gt;Predicate&lt;/font&gt;.LessThan(p.Price, 100), …) &lt;font color="#0000ff"&gt;select &lt;/font&gt;p&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;but it would just work fine (for reasons outlined in my &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/09/14/who-ever-said-linq-predicates-need-to-be-boolean-valued.aspx"&gt;Who ever said LINQ predicates need to be Boolean-valued?&lt;/a&gt; post). However, let’s look at the problem step-by-step, inside-out. What’s up with that p.Price thing? How can we still know all the metadata about that guy? Remember, what we’re defining above in a hidden way is a simple lambda expression of type Func&amp;lt;Product, Predicate&amp;gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;p =&amp;gt; &lt;font color="#008080"&gt;Predicate&lt;/font&gt;.AndAlso(&lt;font color="#008080"&gt;Predicate&lt;/font&gt;.LessThan(p.Price, 100), …)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;That is, give it a Product instance and it will give you back a Predicate instance. But we won’t have Product instances till we’ve executed the query, and to execute the query we need to have the predicate first. Err, something’s not quite right yet as we’re turning in circles. The crux is in the use of p.Price somewhere deep inside the lambda expression (in fact, every reference to p is where the snake bites its own tail). We clearly want to have IntelliSense on every p. (“p dot”) showing all the properties on the entity we can use in our predicate. But on the other hand, executing the lambda with some Product instance, we don’t want to traverse the “dot” into the Price property above, as we need to capture the fact we’re putting a condition on the price of the product.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;Columns and values&lt;/h2&gt;  &lt;p&gt;So, that’s where things get a little tricky. What about making the Price property something that behaves just like a decimal (assuming that’s the type we want) – well, possibly in a restricted way, see further – but still knows its own identity (i.e. it’s a representation of an underlying field/column/attribute/… with the name “Price”). Actually, here we already have an opportunity to control what the user can do with the field. Maybe the target-side doesn’t support, say, addition. So, we want to disallow that (statically). It should be clear by now that p.Price should have a type different from a “raw” decimal. It represents a column, that carries an identity, and can be instantiated at some time to become a value. Let’s ignore the latter part for now and just focus on the “column has a name” part (enough to formulate a query expression). Here’s a proposal:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Column
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;Column(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        Name = name;
    }

    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Name { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NullCheck &lt;/span&gt;HasValue
    {
        &lt;span style="color:blue;"&gt;get
        &lt;/span&gt;{
            &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NullCheck&lt;/span&gt;(&lt;span style="color:blue;"&gt;this&lt;/span&gt;, &lt;span style="color:blue;"&gt;false&lt;/span&gt;);
        }
    }

    &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#a31515;"&gt;&amp;quot;[&amp;quot; &lt;/span&gt;+ Name + &lt;span style="color:#a31515;"&gt;&amp;quot;]&amp;quot;&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The class above acts as the base class for any column. As our target domain is “nullable” regardless of the data type (i.e. not discrepancies in nullability based on reference or value type taxonomies), we also provide a HasValue property here, which returns something that acts like a Boolean but captures semantics for use in query translation. Let’s come back to that in a few moments, but dive into the Column subclass for decimal columns first:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Number &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Column
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;Number(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(name)
    {
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison &lt;/span&gt;Equals(&lt;span style="color:#2b91af;"&gt;NumberValue &lt;/span&gt;value)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison&lt;/span&gt;.Equal(&lt;span style="color:blue;"&gt;this&lt;/span&gt;, value);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;&amp;lt;(&lt;span style="color:#2b91af;"&gt;Number &lt;/span&gt;a, &lt;span style="color:#2b91af;"&gt;NumberValue &lt;/span&gt;b)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison&lt;/span&gt;.LessThan(a, b);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;&amp;lt;(&lt;span style="color:#2b91af;"&gt;NumberValue &lt;/span&gt;a, &lt;span style="color:#2b91af;"&gt;Number &lt;/span&gt;b)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison&lt;/span&gt;.GreaterThan(b, a);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    …
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Again, here we have an opportunity to be different. In the above, I’m mimicking the target domain already in that I’m stepping away from the CLR types into target types. For example, here we talk about Number instead of Decimal (maybe because the target domain only has one numerical format). But notice how the operator overloads (I’ve omitted the opposite ones, which are identical in nature) don’t return Booleans but Comparison objects. Again, wait a moment for a peek at the Comparison type. First we need to talk about the difference between Number and NumberValue. NumberValue is the source-side representation of a constant number, e.g. in our sample query the “100” we’re comparing to would be a NumberValue. That’s where the two worlds meet: in writing a query, you simply use literals in your source language of choice, but NumberValue allows us to transition to the target domain smoothly:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NumberValue &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Value
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;NumberValue(&lt;span style="color:blue;"&gt;decimal &lt;/span&gt;value)
    {
        Value = value;
    }

    &lt;span style="color:blue;"&gt;internal decimal &lt;/span&gt;Value { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;Value.ToString();
    }

    &lt;span style="color:blue;"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NumberValue&lt;/span&gt;(&lt;span style="color:blue;"&gt;decimal &lt;/span&gt;x)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NumberValue&lt;/span&gt;(x);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    …
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Value is a trivial empty base class (just to have a base class in places where we need it to make our code as generic as possible). The only way to construct a NumberValue is by an implicit operator that (and that’s where things are seamless) “lifts” the CLR value into our domain-specific representation. Notice you could perfectly have additional such conversions that allow you to take in other numerical types, causing them to be normalized to the common type the target language knows about.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Comparisons&lt;/h2&gt;

&lt;p&gt;Now we know about the leaf nodes of the predicate trees, namely columns and values, we can turn to their parents. Predicates are based on conditions, that can be of various kind. Relational operators, null checks, string matching, etc are a few samples of such possibilities. What about the LessThan comparison?&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Predicate
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;Comparison(&lt;span style="color:#2b91af;"&gt;PredicateType &lt;/span&gt;type, &lt;span style="color:#2b91af;"&gt;Column &lt;/span&gt;column, &lt;span style="color:#2b91af;"&gt;Value &lt;/span&gt;value)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(type)
    {
        Column = column;
        Value = value;
    }

    &lt;font color="#0000ff"&gt;internal &lt;/font&gt;&lt;span style="color:#2b91af;"&gt;Column &lt;/span&gt;Column { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Value &lt;/span&gt;Value { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:blue;"&gt;string &lt;/span&gt;op = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;

        &lt;span style="color:blue;"&gt;switch &lt;/span&gt;(Type)
        {
            &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.LessThan:
                op = &lt;span style="color:#a31515;"&gt;&amp;quot;&amp;lt;&amp;quot;&lt;/span&gt;;
                &lt;span style="color:blue;"&gt;break&lt;/span&gt;;&lt;br /&gt;            …
        }

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;Column.ToString() + &lt;span style="color:#a31515;"&gt;&amp;quot; &amp;quot; &lt;/span&gt;+ op + &lt;span style="color:#a31515;"&gt;&amp;quot; &amp;quot; &lt;/span&gt;+ (Value == &lt;span style="color:blue;"&gt;null &lt;/span&gt;? &lt;span style="color:#a31515;"&gt;&amp;quot;null&amp;quot; &lt;/span&gt;: Value.ToString());
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison &lt;/span&gt;LessThan(&lt;span style="color:#2b91af;"&gt;Column &lt;/span&gt;column, &lt;span style="color:#2b91af;"&gt;Value &lt;/span&gt;value)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(column == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;column&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(value == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotSupportedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Cannot apply comparison operator with a null value argument.&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.LessThan, column, value);
    }

    …&lt;br /&gt;}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Obviously, you can envision much more such factory methods. The key here is that all of those comparisons represent (part of) a predicate (see further) but are purely a representation instead of something executable locally. I.e. writing p.Price &amp;gt; 100 will result in a Comparison object with Column set to the Number(Column) pointing a the “Price” column, and Value set to a NumberValue carrying the decimal value of 100. We’ve just created a domain-specific representation of the essential building blocks of predicates.&lt;/p&gt;

&lt;p&gt;Our NullCheck we met earlier is built in a very similar way, although it only refers to a column (it’s a unary operator so to speak):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NullCheck &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Comparison
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;NullCheck(&lt;span style="color:#2b91af;"&gt;Column &lt;/span&gt;column, &lt;span style="color:blue;"&gt;bool &lt;/span&gt;isNull)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(isNull ? &lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.IsNull : &lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.IsNotNull, column, &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    {
        IsNull = isNull;
    }

    &lt;span style="color:blue;"&gt;internal bool &lt;/span&gt;IsNull { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NullCheck &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;!(&lt;span style="color:#2b91af;"&gt;NullCheck &lt;/span&gt;check)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NullCheck&lt;/span&gt;(check.Column, !check.IsNull);
    }

    &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:blue;"&gt;return base&lt;/span&gt;.ToString();
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Notice we just play the rules of Booleans, and you can negate a null-check to get a not-null—check. Dead easy.&lt;/p&gt;

&lt;p&gt;Actually there’s a special type of column that needs special treatment: Boolean columns (like p.IsInStock) can be used as a condition straight away (i.e. leaving off the == true comparison). That means a Boolean column should be implicitly convertible into a Condition:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Column
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;Boolean(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(name)
    {
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;!(&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;a)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison&lt;/span&gt;.Equal(a, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BooleanValue&lt;/span&gt;(&lt;span style="color:blue;"&gt;false&lt;/span&gt;));
    }

    &lt;span style="color:blue;"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;a)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Comparison&lt;/span&gt;.Equal(a, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BooleanValue&lt;/span&gt;(&lt;span style="color:blue;"&gt;true&lt;/span&gt;));
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    …
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Again I’ve omitted a bunch of operator overloads (like ==, !=) that are quite predictable.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Predicates&lt;/h2&gt;

&lt;p&gt;Finally the predicates themselves. Comparisons already are predicates, hence their base class being Predicate. However, predicates need to be combinable using Boolean operators, so we need a bit of plumbing there as well:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Predicate
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;Predicate(&lt;span style="color:#2b91af;"&gt;PredicateType &lt;/span&gt;type)
    {
        Type = type;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PredicateType &lt;/span&gt;Type { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;&amp;amp;(&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;a, &lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;b)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BinaryPredicate&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.And, a, b);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;|(&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;a, &lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;b)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BinaryPredicate&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.Or, a, b);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;!(&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;a)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;UnaryPredicate&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.Not, a);
    }

    &lt;span style="color:blue;"&gt;public static bool operator false&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;a)
    {
        &lt;span style="color:green;"&gt;// Used by operator &amp;amp;&amp;amp; (7.11.2)
        // x &amp;amp;&amp;amp; y --&amp;gt; T.false(x) ? x : T.&amp;amp;(x,y)
        &lt;/span&gt;&lt;span style="color:blue;"&gt;return false&lt;/span&gt;;
    }

    &lt;span style="color:blue;"&gt;public static bool operator true&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;a)
    {
        &lt;span style="color:green;"&gt;// Used by operator || (7.11.2)
        // x || y --&amp;gt; T.true(x) ? x : T.|(x,y)
        &lt;/span&gt;&lt;span style="color:blue;"&gt;return false&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The interesting thing here is that the operators &amp;amp;&amp;amp; and || are not overloadable by themselves. The C# specification, section 7.11, details how short-circuiting operators &amp;amp;&amp;amp; and || are defined in terms of more basic building blocks: &amp;amp;, |, true and false. So, we play a trick above: by defining operator overloads for true and false (you can think of those as “has value true” and “has value false” checks), we can force the overloads for &amp;amp; and | to be called at all times, eliminating short-circuiting behavior. Here’s a sample:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;p.Name == &lt;font color="#800000"&gt;“Chai”&lt;/font&gt; &amp;amp;&amp;amp; p.Price &amp;lt; 100&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Both sides of the &amp;amp;&amp;amp; are Comparison objects, which have an overload for the &amp;amp; operator, in addition to the false operator (the || case is defined symmetrically in terms of | and true), so the expression above turns into:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#008080"&gt;Comparison &lt;/font&gt;left = p.Name == &lt;font color="#800000"&gt;“Chai”&lt;/font&gt;;

    &lt;br /&gt;&lt;font color="#008080"&gt;Predicate&lt;/font&gt;.false(left) ? left : &lt;strong&gt;left &amp;amp; (p.Price &amp;lt; 100)&lt;/strong&gt;;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;By returns “false” from the “false” call (I know, it gets abstract), we always end up in the &lt;strong&gt;bold&lt;/strong&gt; part of the conditional expression above, forcing the &amp;amp; operator overload to be called (so, we’re in control again). And actually, it’s not much of a trick after all: by returning “false” from both the “false” and “true” operators, we actually say: “we don’t know yet whether this thing is true or false, please be pessimistic and don’t try to short-circuit this evaluation” (in a sneaky way mumbling to ourselves: “and we’ll do the rest, as you’ll blindly call us on either &amp;amp; or |”).&lt;/p&gt;

&lt;p&gt;Now it should be clear that Boolean operators “just work” based on the operator overloads above. The UnaryPredicate returned from ! is straightforward, and so is the BinaryPredicate on &amp;amp; and |, so let’s show just one of the two:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BinaryPredicate &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Predicate
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;BinaryPredicate(&lt;span style="color:#2b91af;"&gt;PredicateType &lt;/span&gt;type, &lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;left, &lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;right)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(type)
    {
        Left = left;
        Right = right;
    }

    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;Left { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;Right { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:blue;"&gt;string &lt;/span&gt;op = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;

        &lt;span style="color:blue;"&gt;switch &lt;/span&gt;(Type)
        {
            &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.And:
                op = &lt;span style="color:#a31515;"&gt;&amp;quot;and&amp;quot;&lt;/span&gt;;
                &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
            &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PredicateType&lt;/span&gt;.Or:
                op = &lt;span style="color:#a31515;"&gt;&amp;quot;or&amp;quot;&lt;/span&gt;;
                &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
        }

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot; &lt;/span&gt;+ Left.ToString() + &lt;span style="color:#a31515;"&gt;&amp;quot; &amp;quot; &lt;/span&gt;+ op + &lt;span style="color:#a31515;"&gt;&amp;quot; &amp;quot; &lt;/span&gt;+ Right.ToString() + &lt;span style="color:#a31515;"&gt;&amp;quot;)&amp;quot;&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;No surprises here. So ultimately, the expression &lt;em&gt;p.Name == &lt;font color="#800000"&gt;“Chai”&lt;/font&gt; &amp;amp;&amp;amp; p.Price &amp;lt; 100&lt;/em&gt; results in a Predicate instance that carries all the semantics of the predicate and that can be translated (by means of a visitor over our AST representation) into the target domain. Here’s the PredicateType enum that illustrates the breadth of the predicate expressiveness:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;enum &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PredicateType
&lt;/span&gt;{
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
    Equal,
    NotEqual,
    IsNull,
    IsNotNull,
    StartsWith,
    EndsWith,
    Contains,
    Matches,
    And,
    Or,
    Not,
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Entities&lt;/h2&gt;

&lt;p&gt;We have all the materials to be successful in building up a Predicate given an entity object, like Person. Remaining question is how to write such an entity type in a straightforward way, given that the properties need to be subtypes of the Column class (like Number, (our own) Boolean, etc). Here’s a naive attempt:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Product
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;String &lt;/span&gt;Name { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;String&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;productName&amp;quot;&lt;/span&gt;); } }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Number &lt;/span&gt;Price { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Number&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;unitPrice&amp;quot;&lt;/span&gt;); } }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Brr, that’s by no means a nice representation. We’re stating the obvious a number of times: Name is a String (again, one of our subclasses of Column, maybe it should be called StringColumn after all, oh well), referring to a column with name “productName”. Same deal for Price. Lots of boilerplate here just to be able to write queries against a container of such objects. Ideally, we’d be able to write something like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Product
&lt;/span&gt;{
    [&lt;span style="color:#2b91af;"&gt;Column&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;productName&amp;quot;&lt;/span&gt;)]
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;String &lt;/span&gt;Name { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; } }

    [&lt;span style="color:#2b91af;"&gt;Column&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;unitPrice&amp;quot;&lt;/span&gt;)]
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Number &lt;/span&gt;Price { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; } }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Question is how we can magically populate those properties. There are lots of tricks to do this; I’ll illustrate one below. But first, the model above doesn’t allow us to use the same type for the results of the query (we have no place to stick values). In the typical LINQ providers world, that’s a problem. In more exotic scenarios, we might just want to use LINQ to formulate a query, send it to a server and get some kind of visualization of the results back other than raw data. If the latter is the case (as it turned out to be for the problem this blog post is inspired by), this restriction is not a problem. However, even if we’d have to write a “classic” LINQ provider that allows users to return data, you could hack up a solution that looks like this. Maybe I’ll cover that another time as it’s quite an elegant approach to the problem.&lt;/p&gt;

&lt;p&gt;Back to reality: being able to formulate the query requires us to populate the entity object instance with “good” values for its column properties. How did we get here? Well, we don’t have a mechanism anymore that can capture things like p.Name (without causing client-side evaluation). I say “anymore” because we’ve given up expression trees which exactly have that power. In order to populate the properties on the entity type, we could sacrifice the inheritance hierarchy and require the user to derive from some base class called Entity. Again, if we’re just interested in formulating a query, the entity object doesn’t have to do much more than act as a client-side metadata-container in the local type system, so this restriction shouldn’t be a stumble block:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Product &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Entity
&lt;/span&gt;{
    [&lt;span style="color:#2b91af;"&gt;Column&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;productName&amp;quot;&lt;/span&gt;)]
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;String &lt;/span&gt;Name { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;String&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt;); } }

    [&lt;span style="color:#2b91af;"&gt;Column&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;unitPrice&amp;quot;&lt;/span&gt;)]
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Number &lt;/span&gt;Price { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Number&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Price&amp;quot;&lt;/span&gt;); } }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Now, what does the ColumnAttribute (used for mapping purposes) look like?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;[&lt;span style="color:#2b91af;"&gt;AttributeUsage&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;AttributeTargets&lt;/span&gt;.Property, Inherited = &lt;span style="color:blue;"&gt;false&lt;/span&gt;, AllowMultiple = &lt;span style="color:blue;"&gt;false&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ColumnAttribute &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Attribute
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;readonly string &lt;/span&gt;name;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;ColumnAttribute(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        &lt;span style="color:blue;"&gt;this&lt;/span&gt;.name = name;
    }

    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Name
    {
        &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;name; }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Given this, the role of the Entity base class will be to reflect upon the entity object itself, resolve the mapping attributes, new up column objects (like Number, String, etc), carrying the column they refer to:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Number &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Column
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;Number(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(name)
    {
    }&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Here’s a possible simple implementation of the Entity constructor:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Entity
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;Entity()
    {
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;prop &lt;span style="color:blue;"&gt;in this&lt;/span&gt;.GetType().GetProperties())
        {
            &lt;span style="color:blue;"&gt;var &lt;/span&gt;mapping = prop.GetCustomAttributes(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;ColumnAttribute&lt;/span&gt;), &lt;span style="color:blue;"&gt;false&lt;/span&gt;).Cast&amp;lt;&lt;span style="color:#2b91af;"&gt;ColumnAttribute&lt;/span&gt;&amp;gt;().SingleOrDefault();
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(mapping != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            {
                &lt;span style="color:blue;"&gt;var &lt;/span&gt;column = prop.PropertyType.GetConstructor(&lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.Instance | &lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.NonPublic, &lt;span style="color:blue;"&gt;null&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] { &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;string&lt;/span&gt;) }, &lt;span style="color:blue;"&gt;null&lt;/span&gt;).Invoke(&lt;span style="color:blue;"&gt;new object&lt;/span&gt;[] { mapping.Name });
                prop.SetValue(&lt;span style="color:blue;"&gt;this&lt;/span&gt;, column, &lt;span style="color:blue;"&gt;null&lt;/span&gt;);
            }
        }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Nothing more than some reflection voodoo to find all the properties, corresponding mappings, private property setters and invoke the constructor for the column type required, passing in the column mapping value. “Cooperative instantiation” if you really want to hear a fancy word that summarizes it all :-).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;The result&lt;/h2&gt;

&lt;p&gt;Let’s write a query and see how all of this works in concert. To be able to write such a query I’m going to provide a dummy implementation of a Source&amp;lt;T&amp;gt;, in order to allow the query expression pattern to work:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Source&lt;/span&gt;&amp;lt;T&amp;gt; &lt;span style="color:blue;"&gt;where &lt;/span&gt;T : &lt;span style="color:blue;"&gt;new&lt;/span&gt;()
{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Predicate &lt;/span&gt;_predicate;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Source&lt;/span&gt;&amp;lt;T&amp;gt; Where(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:#2b91af;"&gt;Predicate&lt;/span&gt;&amp;gt; where)
    {
        _predicate = where(&lt;span style="color:blue;"&gt;new &lt;/span&gt;T());
        &lt;span style="color:blue;"&gt;return this&lt;/span&gt;;
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Now we can target this source with a LINQ query as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;p &lt;span style="color:blue;"&gt;in new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Source&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt;() &lt;span style="color:blue;"&gt;where &lt;/span&gt;p.Price &amp;gt; 100 &amp;amp;&amp;amp; p.Name == &lt;span style="color:#a31515;"&gt;&amp;quot;Chai&amp;quot; &lt;/span&gt;&lt;span style="color:blue;"&gt;select &lt;/span&gt;p;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Notice how all the operator overloads do their thing:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image_thumb_3.png" width="740" height="49" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The user can’t tell the difference with a regular query (i.e. against CLR types) but can’t fall off the ship either now: no exotic methods will be allowed in the expression if they don’t participate in the typing for the Predicate, Comparison, etc. Obviously, you can still substitute parts of the expression by local values (that can be retrieved by doing whatever you wish) but the other way around – trying to use the entity column references like p.Price and p.Name – won’t work:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image_thumb_4.png" width="1033" height="111" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;From an operation point of view, how did we manage to get the Predicate instance that represents the whole where clause? Take a look at the Where method definition:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Source&lt;/span&gt;&amp;lt;T&amp;gt; Where(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:#2b91af;"&gt;Predicate&lt;/span&gt;&amp;gt; where)
{
    _predicate = where(&lt;span style="color:blue;"&gt;new &lt;/span&gt;T());
    &lt;span style="color:blue;"&gt;return this&lt;/span&gt;;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The only thing to realize here is that T, which is substituted for Product in the sample, is not a concrete instance of the entity type, but merely a metadata container as discussed before. In a bottom-up fashion, our query above translates into a Predicate as follows:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;new T() gives us a new Product object, where the base constructor takes care of resolving the column mappings&lt;/li&gt;

  &lt;li&gt;calling the “where” delegate (which refers to the lambda expression from the query expression) will evaluate like this:&lt;/li&gt;

  &lt;ul&gt;
    &lt;li&gt;p.Price becomes a Number, as instantiated by the constructor trick above and pointing at the unitPrice column;&lt;/li&gt;

    &lt;li&gt;p.Price &amp;gt; 100 causes the 100 to become a NumberValue (through the implicit conversion), and the comparison becomes a Comparison through the &amp;gt; operator overload;&lt;/li&gt;

    &lt;li&gt;similar things happen for p.Name == “Chai”;&lt;/li&gt;

    &lt;li&gt;the two Comparison objects are combined through the &amp;amp; operator overload (together with the “false” operator trick), this produces a Predicate instance;&lt;/li&gt;

    &lt;li&gt;we’re done…&lt;/li&gt;
  &lt;/ul&gt;
&lt;/ul&gt;

&lt;p&gt;Under the debugger, the result looks like this (thanks to the ToString implementation):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://www.bartdesmet.info/images_wlw/HelpDrowninginExpressionTreesWhatNow_114D3/image_thumb_5.png" width="800" height="273" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ah, I like it!&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Download&lt;/h1&gt;

&lt;p&gt;You can find the code of this blog post &lt;a href="http://bartdesmet.net/download/DrowningInExpressionTrees.zip"&gt;here&lt;/a&gt;. All usual warnings apply: no quality assurance was carried out, use at your own risk, and blahblah.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Cheers!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14200" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>LINQ and The Matrix – Introducing MLinq</title><link>http://community.bartdesmet.net/blogs/bart/archive/2009/02/10/linq-and-the-matrix-introducing-mlinq.aspx</link><pubDate>Tue, 10 Feb 2009 18:46:55 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14186</guid><dc:creator>bart</dc:creator><slash:comments>12</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14186</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2009/02/10/linq-and-the-matrix-introducing-mlinq.aspx#comments</comments><description>&lt;p&gt;Today we’ll take a look at project “MLinq”, a very simple way to perform symbolic matrix calculations based on LINQ expression trees.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;But first, why would you even want to do this? Let me tell you I’m a big believer of the power of mathematical notation. Say you’ve been asked to write a piece of code that will carry out rotation of points in an n-dimensional space. To simplify matters, just consider two dimensions. Lots of readers will know this isn’t that hard using matrices:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;img src="http://bartdesmet.info/images/rotationmatrix.png" alt="" /&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So far so good, but now you need to know matrix multiplication in order to concretize the formula for both coordinates. Not a big deal for this particular case, but composability suffers: next you want to take the output of this rotation and feed it in to a transposition, another rotation, and so on. Wouldn’t it be nice just to write the formula as-is and let the system figure out how to turn it into execution? Obviously matrices are just the tip of the iceberg, arbitrary mathematical expressions can be represented in a symbolic format and turned to execution somehow. However, we don’t intend to write a whole symbolic math framework as part of the journey, as others have done this before (Maple, Matlab, Mathematica, to name a few)...&lt;/p&gt;  &lt;p&gt;Let’s go back to our sample of matrix multiplication. What we’re after is something along those lines:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;t = &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Symbol&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;t&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;p = &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Symbol&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;&amp;gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;p&amp;quot;&lt;/span&gt;);

&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt; rotate = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[2, 2] { { &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Cos(t), -&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Sin(t) },
                                                         { &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Sin(t),  &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Cos(t) } };

&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt; point  = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[2, 1] { { p.X() },
                                                         { p.Y() } };

&lt;span style="color:blue;"&gt;var &lt;/span&gt;rot = (rotate * point).Compile&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;&amp;gt;&amp;gt;(p, t);

&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(rot(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;(1, 0), &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.PI / 4));&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;First we define two symbolic constants, t and p. The first symbol, t, stands for the rotation angle (theta) in radians; the second symbol, p, stands for the point to rotate. Next, we define two matrices: one for the rotation matrix (using factory methods for the symbolic representation of cos(theta) and sin(theta)), and another one for the components of the point (actually the X and Y over there could benefit from some dynamic typing features, see further, as the empty method call parentheses pairs are aesthetically unpleasing). Where the magic happens is in the line below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;rot = (rotate * point).Compile&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;&amp;gt;&amp;gt;(p, t);&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we do a bit too much all at once, but it should still be comprehendible enough. First we multiply the two matrices in a “natural” way (you can already smell operator overloading everywhere, don’t ya?), and friendly ask the resulting expression to compile itself into a delegate that given a point and a rotation angle carries out the rotation, returning the resulting point.&lt;/p&gt;

&lt;p&gt;Once we have all of this, we have a compiled piece of code at our service to rotate as much points as we see fit to. The sample above prints the following to the screen, rotating point (1,0) over an angle of 45° (counter-clockwise that is):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(0.707106781186548,0.707106781186547)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;… something every self-respecting math-aware programmer should have predicted almost instantaneously.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Matrix expressions&lt;/h1&gt;

&lt;p&gt;The first piece of glue we need to get this to work is a way to express matrices. Core question becomes what makes up a matrix. The answer is: cells. What do we want those cells to contain? Answer: expressions. So we end up with an array of cells (let’s stick with two dimensions as we’re talking about matrices and not a higher-order construct like tensors).&lt;/p&gt;

&lt;p&gt;Next, what can we do with a single matrix by itself? It makes sense to be able to retrieve an arbitrary cell’s “value”, i.e. the expression that lives in the cell with indices i and j. Notice this “value” isn’t actually a value, it’s an expression representing the cell’s contents in a symbolic way (e.g. x + y, where x and y come from somewhere, maybe as a result of adding together two matrices of the same dimensions).&lt;/p&gt;

&lt;p&gt;Now that we know our intent with individual matrices, what about operations on one or more matrices, like negation, addition, subtraction, multiplication, and more matrix-specific operations like transposition and calculating the determinant of a matrix? An obvious choice here is to leverage the power of operator overloading. Say we want to add up two matrices, what will the result look like? Assuming the dimensions of both arrays match up (a requirement to add two matrices together), each cell will consist of an expression that is the sum of the corresponding expressions in both the input matrices. In other words, we do cell-by-cell addition. Operations like multiplication are a bit more involved though.&lt;/p&gt;

&lt;p&gt;An important question in this whole discussion is whether we want to build up the individual cell expressions at the time a matrix operation is carried out (like addition), or we just want to keep around the fact we applied an operation between different matrices, without building up the expressions for individual cells. In some sense, the former approach is eager while the latter is lazy. And actually, the lazy approach makes sense as the user might just be interested in retrieving the contents of cell (123, 654) after carrying out a bunch of operations on 1024x1024 matrices. It would clearly be a waste of effort to build up expression trees for all other cells. This said, it should be possible to forcefully build up the resulting (symbolic) matrix expression if the user thinks that’s the thing to do (maybe because all cell values are needed). So we’ll go with the lazy variant as the foundation.&lt;/p&gt;

&lt;p&gt;Enough about design, let’s go into implementation. Or wait, one more thing: we’ll treat expressions as immutable for very good reasons and stay in a functional world as much as possible. This said, here’s the class with factory methods for matrices (omitted null checks and such for clarity):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NewMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; New&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[,] elements)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NewMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;(elements);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BinaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; Sum&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; left, &lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; right)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SumMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;(left, right);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BinaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; Product&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; left, &lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; right)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ProductMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;(left, right);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;UnaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; Negate&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; operand)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NegateMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;(operand);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;UnaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; Transpose&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; operand)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;TransposeMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;(operand);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Determinant&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; operand)
    {
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotImplementedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Left as an exercise for the reader.&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;For instance, to get into matrix world, we have to start by calling MatrixExpression.New&amp;lt;T&amp;gt; at some point. This takes in a two-dimensional array of LINQ expression trees that represent, symbolically, the contents of the matrix’s cells. I didn’t want to call this guy a “constant expression” because of its possibly parameterized nature (containing x’s and y’s). The other operators are quite easy to grasp I guess: most of them build up new matrix expressions based on existing ones, with the exception of Determinant that returns to LINQ expression tree land (and is left as a fun exercise for the reader :-)). In essence all of those play the role of constructors, which will become more convenient once we have operator overloads in place (see further).&lt;/p&gt;

&lt;p&gt;So, what does a matrix expression by itself look like?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;MatrixExpression(&lt;span style="color:#2b91af;"&gt;MatrixExpressionType &lt;/span&gt;type)
    {
        NodeType = type;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;&lt;span style="color:blue;"&gt;this&lt;/span&gt;[&lt;span style="color:blue;"&gt;int &lt;/span&gt;i, &lt;span style="color:blue;"&gt;int &lt;/span&gt;j]
    {
        &lt;span style="color:blue;"&gt;get
        &lt;/span&gt;{
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i &amp;lt; 0 || i &amp;gt;= Rows)
                &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentOutOfRangeException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;i&amp;quot;&lt;/span&gt;);&lt;br /&gt;
&lt;br /&gt;&lt;br /&gt;            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(j &amp;lt; 0 || j &amp;gt;= Columns)
                &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentOutOfRangeException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;j&amp;quot;&lt;/span&gt;);

            &lt;span style="color:blue;"&gt;return &lt;/span&gt;Retrieve(i, j);
        }
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpressionType &lt;/span&gt;NodeType { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public int &lt;/span&gt;Rows { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;internal set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public int &lt;/span&gt;Columns { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;internal set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;internal abstract &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Retrieve(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i, &lt;span style="color:blue;"&gt;int &lt;/span&gt;j);

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;ToBLOCKED EXPRESSION
    {&lt;br /&gt;        &lt;span style="color:green;"&gt;// See further.&lt;br /&gt;&lt;/span&gt;    }

    &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
    {
&lt;span style="color:green;"&gt;        // See further.&lt;br /&gt;&lt;/span&gt;    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;R Compile&amp;lt;R&amp;gt;(&lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;[] parameters)
    {&lt;br /&gt;&lt;span style="color:green;"&gt;        // See further.&lt;/span&gt;
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BinaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; &lt;span style="color:blue;"&gt;operator &lt;/span&gt;+(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; left, &lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; right)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;.Sum(left, right);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BinaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; &lt;span style="color:blue;"&gt;operator &lt;/span&gt;*(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; left, &lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; right)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;.Product(left, right);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;UnaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; &lt;span style="color:blue;"&gt;operator &lt;/span&gt;-(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; operand)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;.Negate(operand);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;UnaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; &lt;span style="color:blue;"&gt;operator &lt;/span&gt;~(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; operand)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;.Transpose(operand);
    }

    &lt;span style="color:blue;"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[,] ex)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;.New&amp;lt;T&amp;gt;(ex);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The operator overloads at the bottom shouldn’t be too strange (I’ve omitted a few for simplicity), but maybe the last one deserves some more attention. It’s nothing more but an implicit conversion operator between a two-dimensional array of expressions into a matrix expression, allowing you to write things like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt; rotate = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[2, 2] { { &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Cos(t), -&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Sin(t) },
                                                         { &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Sin(t),  &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Cos(t) } };&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;As you can see, a matrix expression by itself is quite an abstract beast (at least on the instance level). It knows how much rows and columns it has, what its node-type is (just to reduce type casts) and how to retrieve elements (the abstract method will be implemented by the various subclasses and omits bounds checking, we control the bounds of the indices that come in through the indexer and trust implementers to provide a meaningful implementation for indices that are within range). There’s some common functionality though, like pretty printing (ToString). Let’s show that one first:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
{
    &lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringBuilder&lt;/span&gt;();

    sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;{ &amp;quot;&lt;/span&gt;);
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; Rows; i++)
    {
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;{ &amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;j = 0; j &amp;lt; Columns; j++)
        {
            sb.Append(Retrieve(i, j).ToString());
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(j != Columns - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot; }&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != Rows - 1)
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
    }
    sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot; }&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;sb.ToString();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;No surprises here, just calling into ToString on the individual expressions for the cells retrieved through the Retrieve method. So, in essence, ToString forces the cells to be “computed” in a symbolic fashion (e.g. ToString invoked on a summation matrix expression will yield &lt;em&gt;cell-left + cell-right &lt;/em&gt;in a symbolic fashion, e.g. x + y).&lt;/p&gt;

&lt;p&gt;Printing isn’t the most exciting thing though, but we’ll defer the discussion of ToExpression and Compile for a little while longer, and show how to implement concrete matrix expressions first.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Implementing sum and product&lt;/h1&gt;

&lt;p&gt;So, how does a concrete matrix expression implementation look like? Let’s start by taking a quick look at the NewMatrixExpression, which will act as a leaf node in matrix expression trees:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NewMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[,] _elements;

    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;NewMatrixExpression(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[,] elements)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpressionType&lt;/span&gt;.New)
    {
        _elements = elements;

        Rows = elements.GetLength(0);
        Columns = elements.GetLength(1);
    }

    &lt;span style="color:blue;"&gt;internal override &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Retrieve(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i, &lt;span style="color:blue;"&gt;int &lt;/span&gt;j)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_elements[i, j];
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This thing does nothing more but storing a reference to the array of expressions (representing each individual cell), with a trivial implementation of Retrieve on top of it. All we’ve done is abstracted the concept of a two-dimensional array a bit further. (Notice we don’t have true immutability here as we pass in a reference to an existing array of expressions, modifying that will have effects on the whole matrix expression tree defined on top of it…).&lt;/p&gt;

&lt;p&gt;Enough trivialities, let’s turn to the real stuff by taking a glimpse of the SumMatrixExpression:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SumMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;BinaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;SumMatrixExpression(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; left, &lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; right)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpressionType&lt;/span&gt;.Sum, left, right)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(left.Rows != right.Rows || left.Columns != right.Columns)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Dimensions do not match.&amp;quot;&lt;/span&gt;);

        Rows = left.Rows;
        Columns = left.Columns;
    }

    &lt;span style="color:blue;"&gt;internal override &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Retrieve(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i, &lt;span style="color:blue;"&gt;int &lt;/span&gt;j)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(Left.Retrieve(i, j), Right.Retrieve(i, j));
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Still we’re fairly minimalistic in the implementation. We do a little checking of the incoming matrices to make sure the dimensions match, and call into our base class constructor to create a “binary matrix expression” (nothing more than a container for a two MatrixExpression instances, of the same generic parameter T, named Left and Right). The interesting part is Retrieve, which locates the requested cell in both matrices and returns a new expression tree representing the sum of the cells. So, internally matrix expressions perform their operations based on the underlying LINQ expression trees.&lt;/p&gt;

&lt;p&gt;Cool, so how does a product matrix look like? A bit more complicated due to the less trivial mathematical definition, but again relatively straightforward and without boilerplate code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ProductMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;BinaryMatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;private int &lt;/span&gt;_k;

    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;ProductMatrixExpression(&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; left, &lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;T&amp;gt; right)
        : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MatrixExpressionType&lt;/span&gt;.Product, left, right)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(left.Columns != right.Rows)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Dimensions do not line up.&amp;quot;&lt;/span&gt;);

        Rows = left.Rows;
        Columns = right.Columns;

        _k = left.Columns;
    }

    &lt;span style="color:blue;"&gt;internal override &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Retrieve(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i, &lt;span style="color:blue;"&gt;int &lt;/span&gt;j)
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Multiply(Left.Retrieve(i, 0), Right.Retrieve(0, j));

        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;k = 1; k &amp;lt; _k; k++)
            res = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(res, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Multiply(Left.Retrieve(i, k), Right.Retrieve(k, j)));

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;res;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;If you can’t remember how to multiply matrices, open up your favorite search engine to find the answer. You’ll see we’re simply encoding that algorithm above by means of a single for-loop, building up an expression tree that’s a sum of products of cells.&lt;/p&gt;

&lt;p&gt;I’ll leave the implementation of Transpose (rows become columns and vice versa) and Negate (negate every cell) to the reader.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Preparing for evaluation&lt;/h1&gt;

&lt;p&gt;Next we need to take a look at how to evaluate a matrix expression, i.e. how to yield concrete values when supplying substitutions for the symbols. But wait a minute, where to those symbols come from? Say, we’re creating a new matrix and want to stick x and y in some cells, what precisely are x and y? The answer is: ParameterExpression, one of the node types of LINQ expression trees. That by itself is simple enough, but on the surface we might want to abstract that a little to make things more general and more aesthetically pleasing. (Actually, I’m deviating a little here into the world of OMMLinq, where MatrixExpressions are a subset of MathExpressions.) Here’s the glue we want to add:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;_ex;

    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;MathExpression(&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;ex)
    {
        _ex = ex;
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;-(&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;op)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Negate(op._ex));
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;Cos(&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;arg)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Cos&amp;quot;&lt;/span&gt;), arg._ex));
    }
    
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;Sin(&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;arg)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Sin&amp;quot;&lt;/span&gt;), arg._ex));
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SymbolMathExpression &lt;/span&gt;Symbol&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SymbolMathExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T), name));
    }

    &lt;span style="color:blue;"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;ex)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;(ex);
    }

    &lt;span style="color:blue;"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;ex)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;ex._ex;
    }
}

&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SymbolMathExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;MathExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterExpression &lt;/span&gt;_ex;

    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;SymbolMathExpression(&lt;span style="color:#2b91af;"&gt;ParameterExpression &lt;/span&gt;ex) : &lt;span style="color:blue;"&gt;base&lt;/span&gt;(ex)
    {
        _ex = ex;
    }

    &lt;span style="color:blue;"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;SymbolMathExpression &lt;/span&gt;ex)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;ex._ex;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;I’ve omitted a bunch of operators (trigonometry functions, exponentials and logarithms, combinatorials, etc), to reduce the concept of MathExpression to the bare minimum needed for our rotation sample. The key thing here is to see how implicit conversions allow us to go back and forth between LINQ expression trees and math expressions. It’s a bit unfortunate the LINQ expression trees form a closed world (but for a very good reason), so you don’t get to extend that library, ending up with a common base type for all expression tree nodes, so we cook our own. But in essence, once we’re in the world of MathExpression, operations are defined to apply operators and such, without leaking the LINQ expression tree implementation to the outside as part of those operations (unless the raw expression tree is needed, it stays within the walls of this domain-specific expression tree format).&lt;/p&gt;

&lt;p&gt;From the above, you can see how we’ve introduce syntactical sugar for a ParameterExpression in the form of MathExpression.Symbol&amp;lt;T&amp;gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;t = &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Symbol&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;t&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;p = &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Symbol&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;&amp;gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;p&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This feels much more natural and domain-specific than a raw ParameterExpression from LINQ. What Point is defined like shouldn’t be too much of a surprise: two double-valued properties X and Y (and again, immutable).&lt;/p&gt;

&lt;p&gt;Given all of this, you can see how (with additional operators on MathExpression if required) larger and more complex math expressions are built: simply by using the constructor factory methods on MathExpression. That’s how we end up with the definition of the rotation and point matrices:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt; rotate = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[2, 2] { { &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Cos(t), -&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Sin(t) },
                                                         { &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Sin(t),  &lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;.Cos(t) } };

&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt; point  = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[2, 1] { { p.X() },
                                                         { p.Y() } };&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;A few things should stand out here. First, why did I decide to make MatrixExpression “compatible with” a two-dimensional array of LINQ expressions, as opposed to MathExpression objects? The sole reason right now is because of simplification in the implementation of matrices; more specifically, Expression.Add (and its brothers) can’t do operator overload resolution by themselves. For instance, if you’d have two matrices of complex numbers and the ComplexNumber class has an operator overload for +, Expression.Add on two such terms won’t be able to find that operator overload by itself. To avoid distraction on implementing overload resolution rules, I’ve omitted this kind of plumbing (although you can still make it crash by using “unconventional” matrices, e.g. of string elements, which do not have a built-in + operator either).&lt;/p&gt;

&lt;p&gt;The second observation is the use of methods on p to retrieve the point’s coordinates. As I wanted to show the point’s coordinates explicitly (as opposed to multiplying the rotation matrix, which is 2 x 2, with a point, that would look like 1 x 1), I needed a way to extract the coordinates. Simply calling the properties for X and Y doesn’t help, as those return the double values directly. Rather, we need some kind of indirection: a symbolic representation of “take the X coordinate of point p”. I’ve hacked this up using a couple of extension methods:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PointExtensions
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;X(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;ex)
    {
        &lt;span style="color:green;"&gt;// Could be generalized using C# 4.0 &amp;quot;dynamic&amp;quot;.
        &lt;/span&gt;&lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.MakeMemberAccess(ex, ((&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;)ex).Type.GetProperty(&lt;span style="color:#a31515;"&gt;&amp;quot;X&amp;quot;&lt;/span&gt;)));
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;Y(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression &lt;/span&gt;ex)
    {
        &lt;span style="color:green;"&gt;// Could be generalized using C# 4.0 &amp;quot;dynamic&amp;quot;.
        &lt;/span&gt;&lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MathExpression&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.MakeMemberAccess(ex, ((&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;)ex).Type.GetProperty(&lt;span style="color:#a31515;"&gt;&amp;quot;Y&amp;quot;&lt;/span&gt;)));
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Essentially, those build up math expressions based on expression trees that refer to the respective properties. We can’t make this happen automatically while still having somewhat nice syntax. Expression trees can be created for lambda expressions in C#, like – with a closure capturing outer variable p – () =&amp;gt; p.X, but not for “stand-alone” expressions. Even if we’d go with the lambda syntax, using p.X won’t work as p is of type SymbolMathExpression and that doesn’t have an X property by itself (the thing it refers to might have though, as is the case in our sample). That’s where “dynamic” in expression trees would come in handy.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Evaluation&lt;/h1&gt;

&lt;p&gt;So, how do we want to go about evaluating the result of a symbolic computation using those matrix expressions? The answer is, we need to be able to turn cells or the whole matrix into code that can compute values, given the substitutions for the symbols. For example, if we multiply rotate by point and want to know the topmost, leftmost cell’s value, we still need to supply values for the point and the rotation angle, because the cell’s computation might depend on those. So, ultimately we need to turn the cell into the body of a lambda expression that’s parameterized in the symbols.&lt;/p&gt;

&lt;p&gt;Let’s start by looking at the plumbing to evaluate a single cell:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt; res = rotate * point;
&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;cell00 = res[0, 0];
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(cell00);

&lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;fCell00 = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(cell00, p, t);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;f = (&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt;)fCell00.Compile();
&lt;span style="color:blue;"&gt;double &lt;/span&gt;xNew = f(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;(1, 0), &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.PI / 4);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(xNew);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Step-by-step now. The first line is obvious, we take our two matrices and multiply them, giving us back a new matrix containing double-valued (though symbol) cells. Next, we call into the public indexer to retrieve the expression tree for the topmost, leftmost cell. Again, that’s symbolic. You should be able to predicate the third line therefore prints (modulo precise knowledge of Expression.ToString):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;((Cos(t) * p.X) + (-Sin(t) * p.Y))&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As you can see, this contains ingredients from different cells in the original matrices, but composed through LINQ expression tree operations like product and sum. Next, we want to evaluate this, which means we need to get rid of the symbolic representation of p (the pont) and t (the rotation angle). So, we wrap this in a lambda expression that has p and t as parameters. This is what fCell00 is all about. If you’d printf that one, you’d see something like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;(p, t) =&amp;gt; ((Cos(t) * p.X) + (-Sin(t) * p.Y))&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We know the type of p and t, as well as the result (a cell of the matrix is of type double), so we can provide a signature for the to-be-compiled lambda: Point –&amp;gt; double –&amp;gt; double, or in C# style: Func&amp;lt;Point, double, double&amp;gt;. That’s what gets stored in f. And finally, we can call through the delegate, applying our function to a point (x = 1, y = 0) and with a rotation angle of 45° (Pi/4 in radians).&lt;/p&gt;

&lt;p&gt;Quite some boilerplate code to get this to work, but if you want you could compactify the whole thing quite a bit:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;f = (&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt;)&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda((rotate * point)[0,0], p, t).Compile();&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and indeed, this kind of logic would rightfully belong inside MatrixExpression, returning a delegate given cell indices and a (symbols) parameter order.&lt;/p&gt;

&lt;p&gt;Now that we got an idea about how to evaluate a single cell, what about evaluating a whole matrix? What would the result of that be? Clearly, a two-dimensional array of concrete values that are computed based on substitution values for the symbols. That’s exactly what the ToExpression method on MatrixExpression is meant for:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;ToBLOCKED EXPRESSION
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;res =
        &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.NewArrayInit(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T[]), &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, Rows).Select(i =&amp;gt;
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.NewArrayInit(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T), &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, Columns).Select(j =&amp;gt;
                Retrieve(i, j)
            ))).Cast&amp;lt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;gt;() &lt;span style="color:green;"&gt;// Missing generic variance (C# 4.0).
        &lt;/span&gt;);

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;res;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This might look quite dense, but uses the power of LINQ to build up (the expression tree for) an array of symbolic computations, based on the Retrieve method for each individual cell. Insert a few curly braces and it starts to look like nested foreach loops:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;ToBLOCKED EXPRESSION
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;res =
        &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.NewArrayInit(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T[]), &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, Rows).Select(i =&amp;gt;&lt;br /&gt;        {
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.NewArrayInit(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T), &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, Columns).Select(j =&amp;gt;&lt;br /&gt;            {
                Retrieve(i, j);
            });&lt;br /&gt;        })).Cast&amp;lt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;gt;() &lt;span style="color:green;"&gt;// Missing generic variance (C# 4.0).
    &lt;/span&gt;);

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;res;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;What this creates is an expression tree to create an instance of a T[][] array. Notice I’m using jagged arrays because expression trees do not support the creation of multi-dimensional arrays at the time of writing. The use of the Cast&amp;lt;Expression&amp;gt; is interesting. If you emit this, you’ll get a compile error saying: cannot convert an IEnumerable&amp;lt;NewArrayExpression&amp;gt; into an IEnumerable&amp;lt;Expression&amp;gt;. Clearly this is valid because of covariance (IEnumerable&amp;lt;Elephant&amp;gt; should be assignable to IEnumerable&amp;lt;Animal&amp;gt;), but we don’t have this feature at our service for the moment (but C# 4.0 will, yippie, hence my comment in the code).&lt;/p&gt;

&lt;p&gt;Anyway, let’s try the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;MatrixExpression&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;double&lt;/span&gt;&amp;gt; res = rotate * point;
&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;matrix = res.ToBLOCKED EXPRESSION;
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(matrix);

&lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;fMatrix = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(matrix, p, t);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;f = (&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;[][]&amp;gt;)fMatrix.Compile();
&lt;span style="color:blue;"&gt;double&lt;/span&gt;[][] pNew = f(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;(1, 0), &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.PI / 4);
pNew.Print();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Notice the parallels with the code to evaluate a single cell. Now the first Console.WriteLine prints:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;new [] {new [] {((Cos(t) * p.X) + (-Sin(t) * p.Y))}, new [] {((Sin(t) * p.X) + (Cos(t) * p.Y))}}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;or, with some manual touch-ups,&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;new [] { 
      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; new [] {((Cos(t) * p.X) + (-Sin(t) * p.Y))}, 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; new [] {((Sin(t) * p.X) + ( Cos(t) * p.Y))} 

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Clearly the formula we expected for both coordinates, in a LINQ expression tree format. Again, the compilation code is fairly similar, but notice how the return type of the delegate is degraded to a double[][] instead of a Point. We’ll do something about this in a minute, but first the output of the call to Print():&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;{ { 0.707106781186548 }, { 0.707106781186547 } }&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What’s Print anyway? Just a plain extension method on jagged arrays:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Extensions
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Print&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;T[][] array)
    {
        &lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringBuilder&lt;/span&gt;();

        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;{ &amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;int &lt;/span&gt;m = array.Length;
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; m; i++)
        {
            &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = array[i].Length;
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;{ &amp;quot;&lt;/span&gt;);
            &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;j = 0; j &amp;lt; n; j++)
            {
                sb.Append(array[i][j].ToString());
                &lt;span style="color:blue;"&gt;if &lt;/span&gt;(j != n - 1)
                    sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
            }
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot; }&amp;quot;&lt;/span&gt;);

            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != m - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot; }&amp;quot;&lt;/span&gt;);

        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(sb);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;So, what about that broken return type in our delegate (also some kind of covariance, although a double[][] is not really to be treated as a Point in the general case)? Can we do better? With a little hack we can. Say we can trust the user to call Compile on a MatrixExpression, passing in a compatible delegate for the result, like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;rot = (rotate * point).Compile&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;, &lt;span style="color:blue;"&gt;double&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;&amp;gt;&amp;gt;(p, t);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;(Notice this trust relationship is of a kind that we can still throw exceptions in the abuser’s face :-).) It’s clear we can take a look at the generic parameter passed in to Compile, make sure it’s a Func&amp;lt;…&amp;gt;, an extract the return type from it (the last generic parameter). Once we have that, we can emit a LINQ expression tree that wraps the result of a ToExpression call in a Convert expression tree node that makes the return value of the desired type (Expression.Convert is smart enough to find such conversions):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;R Compile&amp;lt;R&amp;gt;(&lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;[] parameters)
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;t = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(R);
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!t.IsGenericType || !t.GetGenericTypeDefinition().Name.StartsWith(&lt;span style="color:#a31515;"&gt;&amp;quot;Func&amp;quot;&lt;/span&gt;))
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Not a Func&amp;lt;...&amp;gt;.&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;a = t.GetGenericArguments();
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;r = a[a.Length - 1];

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;R&amp;gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Convert(&lt;span style="color:blue;"&gt;this&lt;/span&gt;.ToBLOCKED EXPRESSION, r), parameters).Compile();
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Isn’t that beautiful? We just need to have a conversion available from double[][] to Point, obviously one that checks – omitted below – the input dimensions to be conform with expectations for a point’s dimensions (1 x n, with n = 2 in our case, thus a vector):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;(&lt;span style="color:blue;"&gt;double&lt;/span&gt;[][] point)
{
    &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Point&lt;/span&gt;(point[0][0], point[1][0]);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This will do the trick for now, but notice how this makes the intermediate array allocation totally redundant. Can we eliminate that inefficiency? Sure, we have all the materials in the room to do so. We just shouldn’t apply the &amp;quot;Point conversion” from the outside, but extract the two relevant cells from the resulting matrix and feed them in to the Point constructor straight away. Adding this intelligence to our little engine isn’t that hard, even in a somewhat generic way (i.e. “intelligent conversions” as expression tree rewriters), but let’s keep that for another time when we talk about optimizing techniques (tip: try this at home with sparse matrices, i.e. lots of zero-valued cells, and watch the output of simple matrix calculations…).&lt;/p&gt;

&lt;p&gt;Just for the record, here are the results for rotating 10,000,000 (randomly chosen) points with a direct (but naive, i.e. equivalent to the generated expressions from the matrix multiplication, without extracting common subexpressions for sine and cosine calculation) implementation versus our symbolic one (excluding the initial compilation of the lambda):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Symbolic: 00:00:05.2810564 
      &lt;br /&gt;Classic:&amp;#160; 00:00:03.0292995 &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Applying the optimization for Point-conversion I’m hinting at above puts them on par actually (we even did a little better, but that’s just a test noise artifact):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Symbolic: 00:00:03.1099769 
      &lt;br /&gt;Classic:&amp;#160; 00:00:03.2106196&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and if we’d go all the way in the optimizer, we could even eliminate common subexpressions (a bit tricky though, but doable), at the cost of additional compile and analysis time upfront (and getting into territory where LINQ expression trees do not longer help as we need to generate multiple statements now, welcome DLR!).&lt;/p&gt;

&lt;p&gt;Did I tell you I’m a big believer of the power of mathematical notation? Yielding control to the runtime might sound frightening to some, but it has its merits as you can see…&lt;/p&gt;

&lt;p&gt;Have fun!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14186" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx">Crazy Sundays</category></item><item><title>Dude, Where’s My LINQ DML?</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/11/22/dude-where-s-my-linq-dml.aspx</link><pubDate>Sat, 22 Nov 2008 21:53:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14085</guid><dc:creator>bart</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14085</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/11/22/dude-where-s-my-linq-dml.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;On last week’s TechEd EMEA Developers 2008 conference in Spain I redelivered my talk on writing custom LINQ providers, showing off implementations of LINQ to AD and LINQ to SharePoint. One of the questions I received afterwards went along the lines of this blog post’s title: “Dude, where’s my LINQ DML statement support?”. The stock answer to this kind of question points out that it’s up to individual LINQ providers to &lt;em&gt;provide&lt;/em&gt; reasonable support for updating data source entries based on the O/whatever mapping they establish. The typical way this is done is through change tracking of entity objects that have been new’ed up by the provider upon execution of the query through LINQ.&lt;/p&gt;  &lt;p&gt;However, there are cases where this kind of updating is unsatisfactory, especially when dealing with batch updates that don’t require client-side input or computation. For example, when dealing with interactive users, the change tracking driven solution works great, but when updating a set op records based on a certain update pattern (e.g. increase the price of each product with 5%) there’s no need to suck in all entity objects from the data source only to send them back with updates that could well be executed by the target database. Obviously it all depends on the richness of the underlying database’s DML statements, but assuming it’s flexible enough, how to deal with this in the context of LINQ?&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Updateable LINQ to Objects&lt;/h1&gt;  &lt;p&gt;In order to set the scene, let’s investigate what it would take to make LINQ to Objects update-capable. In other words, we want to be able to execute a query and update the retrieved objects in a declarative fashion, i.e. without manual iteration over the query results. To tackle this problem, we can rely on extension methods over IEnumerable&amp;lt;T&amp;gt; in order to provide a method that can apply a certain update-action to each individual object in the sequence. Here’s a possible implementation.&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt;[] updates)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(source == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;source&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(updates == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;updates&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(T item &lt;span style="color:blue;"&gt;in &lt;/span&gt;source)
    {
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; update &lt;span style="color:blue;"&gt;in &lt;/span&gt;updates)
        {
            update(item);
        }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This particular implementation will break the IEnumerable&amp;lt;T&amp;gt; chain as the method is void-returning, but it’s not hard to make it an iterator, yield returning the original sequence elements from the outer loop after the updates have taken place. However, using an iterator in this case might not be the best idea, as the update won’t go through till you start iterating over the resulting sequence because of the lazy nature iterators have. So, let’s stick with void. Next, you might wonder why I chose to pass in an array of update actions instead of a just a single update action. It turns out this doesn’t really matter that much for the in-memory LINQ to Objects case (and indeed, if you just specify a single update action, it will just work fine) but as we’ll see further on, having more manageable individual update actions is a good idea to remote the DML statement. However, in this particular case there’s no way to have more control over the nature of updates, as an Action&amp;lt;T&amp;gt; can be used to point at any procedure, e.g. specified using a statement lambda. Below, I’m illustrating the use of the Update method with more granular update actions:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt; products = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt;() {
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Product &lt;/span&gt;{ Name = &lt;span style="color:#a31515;"&gt;&amp;quot;Chai&amp;quot;&lt;/span&gt;, Price = 123m },
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Product &lt;/span&gt;{ Name = &lt;span style="color:#a31515;"&gt;&amp;quot;Chang&amp;quot;&lt;/span&gt;, Price = 234m },
};

(&lt;span style="color:blue;"&gt;from &lt;/span&gt;p &lt;span style="color:blue;"&gt;in &lt;/span&gt;products
 &lt;span style="color:blue;"&gt;where &lt;/span&gt;p.Price &amp;gt; 100
 &lt;span style="color:blue;"&gt;select &lt;/span&gt;p).Update(
    p =&amp;gt; p.Price *= 0.95,
    p =&amp;gt; p.Name = p.Name.ToUpper()
);

&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;p &lt;span style="color:blue;"&gt;in &lt;/span&gt;products)
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(p.Name + &lt;span style="color:#a31515;"&gt;&amp;quot; - &amp;quot; &lt;/span&gt;+ p.Price);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Notice how other LINQ to Objects operators are used indirectly through query comprehension syntax, more specifically we filter out the items to be updated using a where clause first. As Update performs eager evaluation, enumerating over the source sequence straight away, the results will be visible immediately when iterating over the (now updated) source sequence after the Update invocation. But let’s take a closer look at how we’re specifying the updates above:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;p =&amp;gt; p.Price *= 0.95&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we’re using lambda syntax but notice how the specified lambda doesn’t have a statement body. We’re simply leveraging the fact any value can be ‘converted’ to void, so the lambda above which is of type Product –&amp;gt; decimal can be assigned to an Action&amp;lt;T&amp;gt; where T is Product or, in functional signature syntax, a Product –&amp;gt; void. But there’s nothing that keeps us from writing a far more complex statement body:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;p =&amp;gt; { 
      &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;decimal &lt;/font&gt;oldPrice = p.Price; 

      &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;string &lt;/font&gt;oldName = p.Name; 

      &lt;br /&gt;&amp;#160;&amp;#160; p.Price = oldPrice * 0.95; 

      &lt;br /&gt;&amp;#160;&amp;#160; p.Name = oldName.ToUpper(); 

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Just let your imagination work. Why is this a relevant fact? Our original set of update actions are far more “comprehensible” at runtime for introspection (well, if we turn them in something else than Action&amp;lt;T&amp;gt; which doesn’t produce just plain old IL code) because of their declarative nature.&lt;/p&gt;

&lt;p&gt;There are still quite a few things lacking from our simplistic LINQ to Objects update support mechanism, such as transactional integrity (e.g. assume one of the update actions blows up, how to roll back previous applied updates?) but you get the overall idea.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Updateable remotable LINQ&lt;/h1&gt;

&lt;p&gt;Now, let’s turn the scene and focus on remotable kinds of LINQ, where we want to send off the DML statement to a remote component, e.g. a DBMS system, to execute the update statement. In order to accomplish this goal, we need a way to represent the update statement in some form that we can inspect at runtime to cross-translate it into the remote DML language, e.g. SQL. Luckily we have such a capability in the framework today, with expression trees.&lt;/p&gt;

&lt;p&gt;But what’s in a name? Yes, &lt;em&gt;expression&lt;/em&gt; trees. So, we don’t have the ability to represent arbitrary pieces of procedural statement-driven code like we have above with Action&amp;lt;T&amp;gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; a = i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); }; &lt;font color="#008000"&gt;// works&lt;/font&gt; 

      &lt;br /&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; e = i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); } &lt;font color="#008000"&gt;// fails to compile&lt;/font&gt;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;On the one hand, this is a pity as it limits our expressiveness, but on the other hand it’s a good thing as analyzing arbitrary statement trees would significantly boost the complexity of the translator we’re about to write. However, there’s one significant limitation imposed by this: our update ‘actions’ cannot contain an assignment operator as this can’t be expressed by an expression tree:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;…&amp;gt; e = p =&amp;gt; p.Price *= 0.95;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;So, even if we’d find a way to specify expression trees to build up a DML statement (see further), we can’t make assignments which obviously is a pretty basic piece of functionality when dealing with updates. So, how to work around this? What about the following? Instead of representing an update ‘action’ as one function, we could represent it as two functions: one that acts as a “update target selector” denoting which entity property to update (e.g. p =&amp;gt; p.Price) and one that calculates the new value (e.g. p =&amp;gt; p.Price * 0.95). Together these two carry enough information to express the intent of the update:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;, &lt;span style="color:blue;"&gt;decimal&lt;/span&gt;&amp;gt;&amp;gt; extract = p =&amp;gt; p.Price;&lt;br /&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;, &lt;span style="color:blue;"&gt;decimal&lt;/span&gt;&amp;gt;&amp;gt; update = p =&amp;gt; p.Price * 0.95;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This is a little unfortunate and although there are alternatives (e.g. cooking up some “Updater” object that carries both extractor and updater) most of these yield syntactical clutter, so the bets of having a signature as easy as the following are off:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Using an Updater object, we’d end up with:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;T, R&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;but calling it would be cumbersome:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Update( 
      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;, &lt;font color="#0000ff"&gt;decimal&lt;/font&gt;&amp;gt;(p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95), 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt;(p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper()) 

      &lt;br /&gt;)&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;where Update has a constructor taking in:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;T, R&amp;gt; 

      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;Updater(&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T,R&amp;gt;&amp;gt; extract, &lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T,R&amp;gt;&amp;gt; update)&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ideally, we’d have a way to use tuples to keep the two function expression trees together at all times, also being able to use them in a params:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;font color="#008080"&gt;Tuple&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, R&amp;gt;&amp;gt; &lt;font color="#008000"&gt;/* extract */&lt;/font&gt;, &lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, R&amp;gt;&amp;gt; &lt;font color="#008000"&gt;/* update */&lt;/font&gt;&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and hence the ability to call them easily using some hypothetical call-site syntax:&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;Update( 
    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95), 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper()) 

    &lt;br /&gt;)&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;or even without the additional parentheses pairs (at this time I’m even not thinking about disambiguation, overload resolution, betterness rules, and all this goodness). Or, we could lift the common Expression part out of the tuples, ending up with:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#008080"&gt;Tuple&lt;/font&gt;&amp;lt;R &lt;font color="#008000"&gt;/* extract */&lt;/font&gt;, R &lt;font color="#008000"&gt;/* update */&lt;/font&gt;&amp;gt;&amp;gt;&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Internally, the Update method could now inspect the way the Tuple&amp;lt;R,R&amp;gt; is instantiated, extracting the expression trees for the extract and update parts. However, we’re not all too pleased with the calling syntax that would need to new up tuple objects, obfuscating the intent of the code.&lt;/p&gt;

&lt;p&gt;Let’s go over our needs and observations one more time before we settle on some design:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;We’re bound to the limitations of expression trees; hence: 
    &lt;ul&gt;
      &lt;li&gt;we cannot express an individual update action as one expression (no assignment operation supported); &lt;/li&gt;

      &lt;li&gt;so, an update action needs to be split into an extract and update phase; &lt;/li&gt;

      &lt;li&gt;and, by extension, an update action can only target one value on the entity object at a time. &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;It should be possible to specify multiple update actions at a time to execute them as one unit: 
    &lt;ul&gt;
      &lt;li&gt;this supports transactional updates; &lt;/li&gt;

      &lt;li&gt;we need a way to batch up update actions. &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Introducing IUpdateable&amp;lt;T&amp;gt;&lt;/h1&gt;

&lt;p&gt;By now, we all know about the mysterious IQueryable&amp;lt;T&amp;gt; interface of LINQ. I’ve blogged about it several times, but here’s the key take-away: IQueryable&amp;lt;T&amp;gt; represents a query, wrapping an expression tree denoting the semantics of the intended query, and providing iteration facilities by means of its IEnumerable&amp;lt;T&amp;gt; parent. This, however, only tells half of the story, namely the “IQuery” part. The other half, the “able” part, is not visible on the interface per se, and allows users to extend the query by applying additional query operators that are supplied by means of the extension method in the Queryable class, each of which represents a query operator, like Where, Select, OrderBy, etc. This design allows the implementer of the interface to focus on the query execution part rather than the query construction part which is totally done on behalf of the implementer by means of the extension methods.&lt;/p&gt;

&lt;p&gt;One way to think about IQueryable&amp;lt;T&amp;gt; in general is as a giant state machine. Most of the IQueryable&amp;lt;T&amp;gt; extension methods return an IQueryable&amp;lt;T&amp;gt;, so applying the method (i.e. some query operator) puts us back in the domain of a (new) IQueryable&amp;lt;T&amp;gt;. However, there are other methods like AsEnumerable that allow us to switch to another world, the one of IEnumerable&amp;lt;T&amp;gt;, where we have similar extension methods. To provide update support, we can play a similar trick:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Users write the base query (typically only using filtering) to extract the records that need to be updated – this happens in the IQueryable&amp;lt;T&amp;gt; domain. &lt;/li&gt;

  &lt;li&gt;Next, we transition out of the IQueryable&amp;lt;T&amp;gt; into the IUpdateable&amp;lt;T&amp;gt; domain to provide update support. &lt;/li&gt;

  &lt;li&gt;In IUpdateable&amp;lt;T&amp;gt;, updates can be batched up by calls to a Set method, specifying individual update actions, returning a new IUpdateable&amp;lt;T&amp;gt;. &lt;/li&gt;

  &lt;li&gt;Once all update actions have been specified, an Update method can be called to execute the batch of updates. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A few questions and remarks:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Why starting for IQueryable&amp;lt;T&amp;gt;? In quite some cases, users will want to filter records before applying updates. Right, so what about just having a Where method on IUpdateable&amp;lt;T&amp;gt;? Well, it turns out other operators might be useful as well, such as ordering in case the update would be used to number items based on their ordering (left to the reader as an exercise to think about ways to provide this capability in IUpdateable&amp;lt;T&amp;gt;). Similarly, things like Take could be translated into TOP clauses to apply the update only to the first number of items. And so on. In the end, providing all IQueryable&amp;lt;T&amp;gt; operators first, allowing the user to transition into IUpdateable&amp;lt;T&amp;gt; seems beneficial although some operators likely don’t make much sense (like Select, which would result in updating a projection…). &lt;/li&gt;

  &lt;li&gt;How to iterate over the resulting records, after the update has been applied? This kind of combined approach seems attractive too, but we won’t go there in the scope of the blog post. However, providing this feature shouldn’t be too hard, by means of an AsQueryable method, or by making IUpdateable&amp;lt;T&amp;gt; also IEnumerable&amp;lt;T&amp;gt;, where an iteration triggers execution of the update followed by iteration over the original query that got captured by AsUpdateable originally. This too is left as an exercise for the reader. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Time to present our new interface:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Expression { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
    &lt;span style="color:#2b91af;"&gt;IUpdateProvider &lt;/span&gt;Provider { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;It pretty much follows the design of IQueryable&amp;lt;T&amp;gt; where the Expression property captures the expression tree for the update so far, and the Provider property is used by the extension methods to gain access to a factory method to new up new IUpdateable&amp;lt;T&amp;gt; objects:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateProvider
&lt;/span&gt;{
    &lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; CreateUpdate&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;expression);
    &lt;span style="color:blue;"&gt;int &lt;/span&gt;Update(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt; expression);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In addition, the provider supplies an Update method that will take in the constructed updateable object’s expression tree, carrying out the update and returning the number of affected records. This one can be compared to the Execute method on IQueryProvider. So, how to use those two interfaces now? All of the direct uses will be provided by means of extension methods:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Updateable
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; AsUpdateable&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IQueryable&lt;/span&gt;&amp;lt;T&amp;gt; source)
    {
        &lt;span style="color:#2b91af;"&gt;IUpdateProvider &lt;/span&gt;updateProvider = source.Provider &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateProvider&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(updateProvider == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Update operations not supported by this query provider.&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;updateProvider.CreateUpdate&amp;lt;T&amp;gt;(
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
                &lt;span style="color:blue;"&gt;null&lt;/span&gt;,
                ((&lt;span style="color:#2b91af;"&gt;MethodInfo&lt;/span&gt;)&lt;span style="color:#2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod()).MakeGenericMethod(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T)),
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] { source.Expression }
            )
        );
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; Set&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt;&amp;gt; extract, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt;&amp;gt; update)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Provider.CreateUpdate&amp;lt;T&amp;gt;(
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
                &lt;span style="color:blue;"&gt;null&lt;/span&gt;,
                ((&lt;span style="color:#2b91af;"&gt;MethodInfo&lt;/span&gt;)&lt;span style="color:#2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod()).MakeGenericMethod(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(R)),
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] { source.Expression, extract, update }
            )
        );
    }

    &lt;span style="color:blue;"&gt;public static int &lt;/span&gt;Update&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; updateable)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;updateable.Provider.Update(updateable.Expression);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Here the first method, AsUpdateable, captures an existing IQueryable&amp;lt;T&amp;gt; and checks whether its provider (of type IQueryProvider) supports updates. This piggybacking on top of the existing provider infrastructure is a good thing in general as implementers of an update-capable provider will need to talk to the query provider in order to translate the query portion of the update statement (e.g. a WHERE clause). Being the flip side of it, this means it’s not really possible to sprinkle update support on top of an existing query provider without modifying that provider. You could imagine an additional overload to AsUpdateable that takes in an IUpdateProvider object, and though this would work you’d end up implementing some of the query operators yourself again (e.g. to support filtering). If you know the original query provider’s concrete class and you know it exposes a way to take in an expression tree representing a query, getting back the translated query, there might be a way to avoid duplication (provided the target query language is compositional in nature):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;provider = (&lt;font color="#008080"&gt;SomeSqlQueryProvider&lt;/font&gt;)source.Provider; 

      &lt;br /&gt;&lt;font color="#0000ff"&gt;string &lt;/font&gt;sql = provider.GetSqlStatement(source); 

      &lt;br /&gt;… 

      &lt;br /&gt;&lt;font color="#0000ff"&gt;string &lt;/font&gt;update = &lt;font color="#800000"&gt;“UPDATE “&lt;/font&gt; + … + &lt;font color="#800000"&gt;“ FROM (“&lt;/font&gt; + sql + &lt;font color="#800000"&gt;“)”&lt;/font&gt;; &lt;font color="#008000"&gt;// pseudo-SQL&lt;/font&gt;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But let’s ignore this for now. Other than this, AsUpdateable is straightforward, it takes the original expression tree and wraps it in a MethodCallExpression for the current method. Just like IQueryable&amp;lt;T&amp;gt; does this, the original expression tree gets extended with information about the applied operators represented as method calls.&lt;/p&gt;

&lt;p&gt;The Set method, representing an individual update action, is completely similar. More interesting is its signature: besides of an IUpdateable&amp;lt;T&amp;gt; object, it takes in both the extract and update functions as expression trees, using the principle we talked about earlier.&lt;/p&gt;

&lt;p&gt;Finally, Update is just syntactical sugar on top of an IUpdateable&amp;lt;T&amp;gt; to call into the underlying provider to carry out the update, allowing for a fluent interface design. Ultimately, all of this can be used as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;(&lt;span style="color:blue;"&gt;from &lt;/span&gt;p &lt;span style="color:blue;"&gt;in new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Table&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt;()
 &lt;span style="color:blue;"&gt;where &lt;/span&gt;p.Price &amp;gt; 100
 &lt;span style="color:blue;"&gt;select &lt;/span&gt;p).AsUpdateable()
    .Set(p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95)
    .Set(p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper())&lt;br /&gt; .Update();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Going out in the woods we could start dreaming about integrated syntax that looks like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;from &lt;/span&gt;p &lt;span style="color:blue;"&gt;in new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Table&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt;() 

      &lt;br /&gt;&lt;span style="color:blue;"&gt;where &lt;/span&gt;p.Price &amp;gt; 100 

      &lt;br /&gt;&lt;span style="color:blue;"&gt;update &lt;/span&gt;p.Price *= 0.95, 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; p.Name = p.Name.ToUpper();&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;which might automatically become eager, i.e. the Update call is implicit, or stays lazy (which would mean one can reuse the query/update comprehension expression). VB syntax could be very similar, optionally using the With keyword (Update p With …).&lt;/p&gt;

&lt;p&gt;Enough dreaming for now, this whole expression (more specifically everything before the .Update() part) translates into an expression tree, constructed at runtime with the aid of the Queryable query operators and Updateable update operators, that can be represented as follows using ToString notation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;expression = {value(Table`1[Product]).Where(p =&amp;gt; (p.Price &amp;gt; 100)).AsUpdateable().Set(p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95).Set(p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper())}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now the update provider can go ahead and cross-translate this expression tree into a statement the target data source understands, e.g. a SQL DML statement for UPDATE (I’m not a SQL language expert, so treat the following as conceptual code):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;UPDATE &lt;/font&gt;Products &lt;font color="#0000ff"&gt;WHERE &lt;/font&gt;Price &amp;gt; 100 &lt;font color="#0000ff"&gt;SET &lt;/font&gt;Price *= 0.95, Name = &lt;font color="#0000ff"&gt;TOUPPER&lt;/font&gt;(Name)&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I’ll leave a concrete implementation of an update provider to the inspired reader; a basic prototype for SQL (only allowing columns to be updated with constant string or integer values) worked like a charm. In addition, the reader should feel free to think about how it would be possible (if desirable at all, something to think about as well) to make the “LINQ to Objects with update support” case similar to the remotable case, in terms of used operators (i.e. our current LINQ to Object implementation in the first paragraph doesn’t use Set method calls and isn’t lazy at all).&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14085" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>C# 4.0 Feature Focus - Part 3 - Intermezzo: LINQ's new Zip operator</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx</link><pubDate>Tue, 04 Nov 2008 07:11:43 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14055</guid><dc:creator>bart</dc:creator><slash:comments>23</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14055</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx#comments</comments><description>&lt;p&gt;After &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/11/01/c-4-0-feature-focus-part-2-named-parameters.aspx"&gt;named parameters&lt;/a&gt; and &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx"&gt;optional parameters&lt;/a&gt;, we&amp;#39;ll take a little breadth and deviate a bit from the language specifics to present a new LINQ operator: Zip. Just like a zipper zips two streams of materials together, LINQ&amp;#39;s Zip operator can zip together two sequences. Here&amp;#39;s the signature of the new method:&lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func);&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Sample&lt;/h1&gt;  &lt;p&gt;Given two sequences and a function that combines two elements from both sequences, a sequence of zipped pairs is produced. Here&amp;#39;s a sample:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;[] names = { &lt;font color="#800000"&gt;&amp;quot;Bart&amp;quot;&lt;/font&gt;, &lt;font color="#800000"&gt;&amp;quot;John&amp;quot;&lt;/font&gt; };         &lt;br /&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;[] ages = { 25, 60 };         &lt;br /&gt;        &lt;br /&gt;names.Zip(ages, (name, age) =&amp;gt; name + &lt;font color="#800000"&gt;&amp;quot; is &amp;quot;&lt;/font&gt; + age + &lt;font color="#800000"&gt;&amp;quot; years old.&amp;quot;&lt;/font&gt;);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This produces a sequence with the sentences &amp;quot;Bart is 25 years old.&amp;quot; and &amp;quot;John is 60 years old.&amp;quot;. The lambda syntax for the passed-in function should speak for itself, and notice we&amp;#39;re using extension method invocation here, so names is propagated to become the left-hand side of the method call.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;How Zip works&lt;/h1&gt;  &lt;p&gt;Previously I&amp;#39;ve implemented the Standard Query Operators for reference purposes on the Codeplex site at &lt;a href="http://www.codeplex.com/LINQSQO"&gt;http://www.codeplex.com/LINQSQO&lt;/a&gt;. I won&amp;#39;t update that sample library just yet, but here&amp;#39;s an illustration on how easy Zip is to implement, ignoring exception handling (which is more subtle than you might think, see further):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie1 = first.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie2 = second.GetEnumerator(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(ie1.MoveNext() &amp;amp;&amp;amp; ie2.MoveNext())         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;func(ie1.Current, ie2.Current);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The Zip operation is implemented using iterators inside (&amp;quot;yield return&amp;quot;) and stops as soon as one of the sequences runs out of juice (the case of the asymmetric zipper).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Zip without Zip?&lt;/h1&gt;  &lt;p&gt;As a curiosity, is it actually possible to build Zip out of existing LINQ operators, ignoring performance worries? Unsurprisingly, it turns out this is the case. Here&amp;#39;s how:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;first.Select((x, i) =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; { X = x, I = i }).Join(second.Select((x, i) =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; { X = x, I = i }), o =&amp;gt; o.I, i =&amp;gt; i.I, (o, i) =&amp;gt; func(o.X, i.X));         &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;(Exercise for the reader: think of more alternatives.) How does this work? To explain this we need a bit of vocabulary, so let&amp;#39;s refer to &lt;a href="http://en.wikipedia.org/wiki/Zipper"&gt;Wikipedia&lt;/a&gt; for a second and apply an isomorphism between textile sciences and computer sciences (something in me screams &amp;quot;zip, zipper, zippest&amp;quot;):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;The &lt;strike&gt;bulk&lt;/strike&gt; &lt;font color="#ff0000"&gt;signature&lt;/font&gt; of a &lt;strike&gt;zipper&lt;/strike&gt; &lt;font color="#ff0000"&gt;Zip &lt;/font&gt;consists of two &lt;strike&gt;strips&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences &lt;/font&gt;of &lt;strike&gt;fabric&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;element&lt;/font&gt; t&lt;strike&gt;&lt;font color="#ff0000"&gt;a&lt;/font&gt;&lt;/strike&gt;ype&lt;font color="#ff0000"&gt;s&lt;/font&gt;, each affixed to one of the two &lt;strike&gt;pieces&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequence instances &lt;/font&gt;to be joined, carrying tens or hundreds &lt;font color="#ff0000"&gt;or anything below OutOfMemoryException conditions&lt;/font&gt; of &lt;strike&gt;specially&lt;/strike&gt; &lt;font color="#ff0000"&gt;regularly&lt;/font&gt; &lt;strike&gt;shaped&lt;/strike&gt; &lt;font color="#ff0000"&gt;allocated&lt;/font&gt; &lt;strike&gt;metal&lt;/strike&gt; &lt;font color="#ff0000"&gt;reference-&lt;/font&gt; or &lt;strike&gt;plastic&lt;/strike&gt; &lt;font color="#ff0000"&gt;value-typed&lt;/font&gt; &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements&lt;/font&gt;. (...) The &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate&lt;/font&gt;, operated by &lt;strike&gt;hand&lt;/strike&gt; &lt;font color="#ff0000"&gt;executing Zip&lt;/font&gt;, moves along the &lt;strike&gt;rows&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences&lt;/font&gt; of &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements&lt;/font&gt;. Inside the &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate &lt;/font&gt;is a &lt;strike&gt;Y-shaped&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;strongly-typed &lt;/font&gt;&lt;strike&gt;channel&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;function&lt;/font&gt; that meshes together &lt;strike&gt;or separates&lt;/strike&gt; the opposing &lt;strike&gt;rows&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences&lt;/font&gt; of &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements&lt;/font&gt;, &lt;strike&gt;depending on the direction of its movement&lt;/strike&gt;. The &lt;strike&gt;friction&lt;/strike&gt; &lt;font color="#ff0000"&gt;binding &lt;/font&gt;and &lt;strike&gt;vibration&lt;/strike&gt; &lt;font color="#ff0000"&gt;application&lt;/font&gt; of the &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate &lt;/font&gt;&lt;strike&gt;against&lt;/strike&gt; &lt;font color="#ff0000"&gt;on &lt;/font&gt;the &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements &lt;/font&gt;causes a characteristic &lt;strike&gt;buzzing&lt;/strike&gt; &lt;font color="#ff0000"&gt;callvirt&amp;#39;ing&lt;/font&gt; noise, which is probably &lt;font color="#ff0000"&gt;not&lt;/font&gt; the origin of the name zipper. The name also may have originated in the greater speed and ease with which the two sides of a &lt;strike&gt;zipper&lt;/strike&gt; &lt;font color="#ff0000"&gt;Zip&lt;/font&gt; can be joined, compared to the time needed for &lt;strike&gt;fastening&lt;/strike&gt; &lt;font color="#ff0000"&gt;executing&lt;/font&gt; &lt;strike&gt;laces or buttons&lt;/strike&gt; &lt;font color="#ff0000"&gt;the method above&lt;/font&gt;.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Well, that&amp;#39;s exactly what happens: opposing &lt;strike&gt;rows&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences&lt;/font&gt; of &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements &lt;/font&gt;are combined by a &lt;strike&gt;Y-shaped&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;strongly-typed &lt;/font&gt;&lt;strike&gt;channel&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;function&lt;/font&gt;. How to determine opposing sequence elements? Using Select&amp;#39;s overload that provides (besides the element itself) an index denoting the element&amp;#39;s position in the original sequence. Matching the opposing elements is a matter of joining both sequences, extracting the keys (marked as I in the anonymous type) and combining the selected pairs of elements from both sequences (marked as X in the anonymous type) by feeding them in to the &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate&lt;/font&gt;. I told you the explanation was straightforward, or did I?&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Iterators and exceptions&lt;/h1&gt;  &lt;p&gt;Most of the LINQ operators are implemented using iterators. You might wonder this this is relevant at all. Obviously we need it as LINQ operators need to be lazy. Only when you start fetching results by iterating of the sequence, the internal machinery should kick in. Declaring a query doesn&amp;#39;t cause any execution whatsoever. Internally iterators are implemented as state machines. Every state can do on &amp;quot;yield&amp;quot;, after which the state machine is suspended till the consumer asks for the next element in the sequence being produced by calling MoveNext on the IEnumerator&amp;lt;T&amp;gt; object.&lt;/p&gt;  &lt;p&gt;Our Zip implementation above is turned into an equivalent piece of code (slightly simplified for illustrative purposes):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return new &lt;/font&gt;&lt;font color="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt;(first, second, func);         &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;private sealed class &lt;/font&gt;&lt;font color="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; : &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt;, &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TResult&amp;gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;//&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// Captured iterator method parameters.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //&lt;/font&gt;         &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; _first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; _func;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; _second;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Iterator&amp;#39;s enumerator state and thread affinity.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;State &lt;/font&gt;_state;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private int &lt;/font&gt;_initialThreadId;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Value currently yielded by the iterator&amp;#39;s enumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;TResult _current;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Local variables used by the iterator&amp;#39;s enumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TFirst&amp;gt; _ieFirst;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TSecond&amp;gt; _ieSecond;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Captured iterator method parameters used by enumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Public constructor to create an iterator in the initial ready state.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public&lt;/font&gt; ZipIterator(&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; : &lt;font color="#0000ff"&gt;this&lt;/font&gt;()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._first = first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._second = second;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._func = func;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Private constructor to set state and thread affinity.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;ZipIterator()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Before;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._initialThreadId = &lt;font color="#008080"&gt;Thread&lt;/font&gt;.CurrentThread.ManagedThreadId;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets a new enumerator over the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TResult&amp;gt; &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt;.GetEnumerator()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; iterator;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // Can reuse the current enumerator if thread affinity and state permit it.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(&lt;font color="#008080"&gt;Thread&lt;/font&gt;.CurrentThread.ManagedThreadId == _initialThreadId &amp;amp;&amp;amp; _state == &lt;font color="#008080"&gt;State&lt;/font&gt;.Before)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator = &lt;font color="#0000ff"&gt;this&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;else&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt;();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator.first = &lt;font color="#0000ff"&gt;this&lt;/font&gt;._first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator.second = &lt;font color="#0000ff"&gt;this&lt;/font&gt;._second;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator.func = &lt;font color="#0000ff"&gt;this&lt;/font&gt;._func; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;iterator;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets a new enumerator over the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;IEnumerator &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;.GetEnumerator()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; ((&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt;)&lt;font color="#0000ff"&gt;this&lt;/font&gt;).GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Advances the iterator one yield return at a time.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;bool&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.MoveNext()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;switch&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._state)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Before:         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.first.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.second.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;goto&lt;/font&gt; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended:         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.MoveNext() &amp;amp;&amp;amp; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.MoveNext())         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._current = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.func(&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.Current, &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.Current);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return true&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;font face="Courier New"&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;break&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.After;&lt;/font&gt;       &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return false&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Retting the iterator enumerator is not supported; create a new one instead by calling GetEnumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // The foreach statement does this anyway.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;void&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.Reset()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotSupportedException&lt;/font&gt;();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets the value currently yielded from the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; TResult &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TResult&amp;gt;.Current         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;get&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;_current;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets the value currently yielded from the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;object&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.Current         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;get&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;_current;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // IDisposable implementation.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&amp;#160;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;void&lt;/font&gt; &lt;font color="#008080"&gt;IDisposable&lt;/font&gt;.Dispose()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Internal iterator enumerator states.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;private enum &lt;/font&gt;&lt;font color="#008080"&gt;State&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Before,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Running,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Suspended,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; After         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;font face="Courier New"&gt;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice that the code above holds the middle between the specification (paragraph 10.14 of the C# 3.0 specification) and the actual implementation in the Visual C# 2008 compiler. More specifically, I&amp;#39;ve made the discrete states (which are internally represented as integers) match the ones in the specification, but haven&amp;#39;t gone all the way in matching the code up with the &lt;/p&gt;  &lt;p&gt;Of all this machinery, the MoveNext method is the most interesting one from the iterator&amp;#39;s point of view. Here a state machine is built, rewriting the original iterator block by splitting it into discrete blocks. To perform this transformation, yield return statements are replaced as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&amp;#160;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;yield &lt;/font&gt;a;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;becomes&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;this&lt;/font&gt;._current = a;         &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;this&lt;/font&gt;&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended;         &lt;br /&gt;&lt;font color="#0000ff"&gt;return true&lt;/font&gt;;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Similar rewrites happen for yield break statements, but that&amp;#39;s not relevant here. Furthermore all the iterator block code is placed in a MoveNext method, switching on the current state. The specification only mentions the four states I&amp;#39;ve implemented above, but we&amp;#39;re lucky the number of states for our sample matches up with the number of states that&amp;#39;s specified. In cases where there are more yield statements, more states are needed to suspend the machine and resume at the same point during the next MoveNext call. Other transformations needed include rewriting of loops (things like while don&amp;#39;t really play well with suspension points and need to be rewritten in terms of if/goto, where gotos require additional states). Applying all those tricks gives us:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;bool&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.MoveNext()         &lt;br /&gt;{         &lt;br /&gt;Begin:         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;switch&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._state)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Before:         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.first.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.second.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Running;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;goto&lt;/font&gt; Begin; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Running:&lt;/font&gt;&lt;font face="Courier New"&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended:         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.MoveNext() &amp;amp;&amp;amp; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.MoveNext())         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._current = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.func(&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.Current, &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.Current);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return true&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;font face="Courier New"&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;break&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.After;&lt;/font&gt;       &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return false&lt;/font&gt;;         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Here the local variables used in the iterator block are captured in the initial pass through MoveNext, when state is still set to Before. Strictly speaking we move from Before to Running all the way to the first point where the code gets suspended, but in our case states can be merged quite a bit. In fact the code really produced by the compiler looks like this:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;bool&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.MoveNext()       &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;switch&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._state)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; 0:       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = -1;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.first.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.second.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.MoveNext() &amp;amp;&amp;amp; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.MoveNext())       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;.current = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.func(&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.Current, &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.Current);       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = 1;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return true&lt;/font&gt;;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Resume:       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = -1;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;break&lt;/font&gt;; &lt;/font&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; 1:         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;goto&lt;/font&gt; Resume;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return false&lt;/font&gt;;         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;But &lt;strong&gt;why am I telling you all this&lt;/strong&gt;? Because it&amp;#39;s fascinating? Yes, for that reason too. But I promised to tell you something about exceptions, right? Let me quote from the C# 3.0 specification paragraph 10.14.4.1 first:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;em&gt;(...) The precise action performed by MoveNext depends on the state of the enumerator object when MoveNext is invoked:&lt;/em&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;em&gt;If the state of the enumerator object is &amp;#39;before&amp;#39;, invoking MoveNext:&lt;/em&gt;       &lt;ul&gt;       &lt;li&gt;&lt;em&gt;Changes the state to &amp;#39;running&amp;#39;.&lt;/em&gt; &lt;/li&gt;        &lt;li&gt;&lt;em&gt;Initializes the parameters (including this) of the iterator block to the argument values and instance value saved when the enumerator object was initialized.&lt;/em&gt; &lt;/li&gt;        &lt;li&gt;&lt;em&gt;&lt;font color="#ff0000"&gt;Executes the iterator block from the beginning until execution is interrupted (as described below).&lt;/font&gt;&lt;/em&gt; &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;em&gt;(...)&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;The red line is what&amp;#39;s of interest to us, and you should read it in reverse:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;The code from the beginning of the iterator block till the place where execution is interrupted (i.e. a yield occurs) is executed by MoveNext when transitioning from &amp;#39;before&amp;#39; to &amp;#39;running&amp;#39;.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What if that code contains exception throwing statements?&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(first == &lt;font color="#0000ff"&gt;null&lt;/font&gt;)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;first&amp;quot;&lt;/font&gt;);         &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;/p&gt;   &lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(second == &lt;font color="#0000ff"&gt;null&lt;/font&gt;)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;second&amp;quot;&lt;/font&gt;);       &lt;br /&gt;&lt;/font&gt;    &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie1 = first.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie2 = second.GetEnumerator(); &lt;/font&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(ie1.MoveNext() &amp;amp;&amp;amp; ie2.MoveNext())         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;func(ie1.Current, ie2.Current);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As you can guess, this code won&amp;#39;t get executed till the very first passage through the iterator&amp;#39;s enumerator object&amp;#39;s MoveNext method. Recall what foreach corresponds to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#008080"&gt;V&lt;/font&gt; v &lt;font color="#0000ff"&gt;in &lt;/font&gt;x) &lt;em&gt;embedded-statement&lt;/em&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;becomes (with C the collection type, E the enumerator type, V the local variable type and T the element type)&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;E&lt;/font&gt; e = ((&lt;font color="#008080"&gt;C&lt;/font&gt;)(x)).GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;try&lt;/font&gt; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;V &lt;/font&gt;v;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(&lt;font color="#ff0000"&gt;e.MoveNext()&lt;/font&gt;) {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; v = (&lt;font color="#008080"&gt;V&lt;/font&gt;)(&lt;font color="#008080"&gt;T&lt;/font&gt;)e.Current;         &lt;br /&gt;&lt;em&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; embedded-statement&lt;/em&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;finally &lt;/font&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ...         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So just calling the iterator does nothing that can cause the exceptions to be thrown, until a call is made to MoveNext, e.g. by using a foreach loop. As we want the exception to be thrown straight away when calling Zip with invalid arguments, the right way to implement our Zip method is:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(first == &lt;font color="#0000ff"&gt;null&lt;/font&gt;)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;first&amp;quot;&lt;/font&gt;);         &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;/p&gt;   &lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(second == &lt;font color="#0000ff"&gt;null&lt;/font&gt;)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;second&amp;quot;&lt;/font&gt;);       &lt;br /&gt;      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; ZipInternal(first, second, func);       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; private static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; ZipInternal&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {&lt;/font&gt;     &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie1 = first.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie2 = second.GetEnumerator(); &lt;/font&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(ie1.MoveNext() &amp;amp;&amp;amp; ie2.MoveNext())         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;func(ie1.Current, ie2.Current);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;The addition of Zip to LINQ is a nice one, but not a mind-blower. So I hope you&amp;#39;ll accept my apologies for using this as a lame excuse to nag about the implementation of iterators and their subtle impact on exceptions. Next time: generics co- and contra-variance in C# 4.0.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14055" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>Who ever said LINQ predicates need to be Boolean-valued?</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/09/14/who-ever-said-linq-predicates-need-to-be-boolean-valued.aspx</link><pubDate>Sun, 14 Sep 2008 19:23:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13970</guid><dc:creator>bart</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13970</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/09/14/who-ever-said-linq-predicates-need-to-be-boolean-valued.aspx#comments</comments><description>&lt;p&gt;&lt;u&gt;Note for purists:&lt;/u&gt; This post only speaks for “LINQ predicates”, not – although closely related to - the mathematic concept of a predicate as defined by&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://mathworld.wolfram.com/about/author.html"&gt;Weisstein, Eric W.&lt;/a&gt; &amp;quot;Predicate.&amp;quot; From &lt;a href="http://mathworld.wolfram.com/"&gt;&lt;i&gt;MathWorld&lt;/i&gt;&lt;/a&gt;--A Wolfram Web Resource. &lt;a href="http://mathworld.wolfram.com/Predicate.html"&gt;http://mathworld.wolfram.com/Predicate.html&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;as&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;An operator in &lt;a href="http://mathworld.wolfram.com/Logic.html"&gt;logic&lt;/a&gt; which returns either &lt;a href="http://mathworld.wolfram.com/True.html"&gt;true&lt;/a&gt; or &lt;a href="http://mathworld.wolfram.com/False.html"&gt;false&lt;/a&gt;.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The LINQ provider spectrum&lt;/h1&gt;  &lt;p&gt;Back in the wonderful world of LINQ. This time I’d like to highlight one of the most important properties of LINQ: its flexibility. On various occasions I’ve already stated that the potential of LINQ is infinity², the reason for it being the infinite fan-in (LINQ though C#, VB, F#, PowerShell, various transport mechanisms, etc) multiplied by the infinite fan-out (LINQ to SQL, Entities, XML, Objects, DataSets, SharePoint, Active Directory, Amazon, etc). In this post we forget about the former infinity factor and move on to the latter, where we have a whole spectrum of query provider implementations. The spectrum is bordered by two extremes:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Completely local, through IEnumerable&amp;lt;T&amp;gt; (some will debate whether this is a &lt;em&gt;query provider&lt;/em&gt;). LINQ to Objects and XML fit in this bucket. The cost to implement this is virtually zero, you just need to make sure your API speaks in terms of IEnumerable&amp;lt;T&amp;gt; (e.g. in LINQ to XML we have methods like Descendants that return sequences of XML nodes). On the flip side though, you can’t delegate execution of the query to another execution engine, e.g. by “remoting” the query to SQL. &lt;/li&gt;    &lt;li&gt;Completely remot&lt;em&gt;able&lt;/em&gt;, through IQueryable&amp;lt;T&amp;gt;. LINQ to SQL, SharePoint, Active Directory, Amazon, etc fall under this umbrella. Implementation cost is higher for this type of providers as the expression tree produced by the IQueryable extension methods needs to be turned into whatever domain-specific language you want to target, e.g. SQL, CAML, LDAP, web service calls, etc. However, the potential to control and delegate execution is huge. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Notice the italics for the word remot&lt;em&gt;able&lt;/em&gt; in the latter category: the provider shouldn’t necessarily remote (in the broadest sense of the word, from cross-process to cross-machine) the execution, instead it can be a transformer that rewrites expression trees to optimize or decompose them, etc. Similarly, the provider could be intelligent about distribution of the query execution: maybe it can divide-and-conquer, splitting the work across servers or doing part of the work locally. I’m not a huge fan of the latter “intelligence” (because it becomes too “smart”) as such providers tend to be dishonest about where executes what:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; res = (&lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;products &lt;font color="#0000ff"&gt;where &lt;/font&gt;p.Price &amp;gt; 100 &lt;font color="#0000ff"&gt;select new &lt;/font&gt;{ Name = p.ProductName }).Take(5);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Maybe the provider executes the where-predicate locally, meaning we’d suck in too many rows. Or it might not know how to do a projection remotely, causing us to suck in too many columns. Similarly, the Take operation might not translate well in the target domain causing similar data transmission overhead worries. Personally I prefer explicit transitioning markers using AsEnumerable to clearly delimit the borders of local versus remote execution. Obviously, when remote and local are relatively close to each other (e.g. cross-process) this type of “smartness” might be well-justified (e.g. LINQ to MSI queries a local file; or LINQ to SharePoint might run in an ASP.NET application on the same machine as WSS; or LINQ to SQL could potentially and hypothetically run inside the database relational engine itself). Back to where we were though…&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;LINQ as a language pattern&lt;/h1&gt;  &lt;p&gt;In between those two extremes there’s a whole range of possibilities because of the way &lt;strong&gt;LIN&lt;/strong&gt;Q really works: as a &lt;strong&gt;front-end language pattern&lt;/strong&gt;, just like foreach, lock, using, etc are patterns on top of other stuff (IEnumerable, Monitor, IDisposable, etc). What does that imply? The compiler just knows about LINQ as a set of keywords that can be turned into specific method calls, which happen to reflect query operators. To provide some context, refer to my earlier post on “&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/30/c-3-0-query-expression-translation-cheat-sheet.aspx"&gt;C# 3.0 Query Expression Translation Cheat Sheet&lt;/a&gt;” where you’ll see translation rules like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;&lt;em&gt;x&lt;/em&gt; &lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;em&gt;e&lt;/em&gt; &lt;font color="#0000ff"&gt;where &lt;/font&gt;&lt;em&gt;f&lt;/em&gt; …&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;becomes&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;&lt;em&gt;x&lt;/em&gt; &lt;font color="#0000ff"&gt;in &lt;/font&gt;(&lt;em&gt;e&lt;/em&gt;).Where(&lt;em&gt;x&lt;/em&gt; =&amp;gt; &lt;em&gt;f&lt;/em&gt;) …&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;That’s just it, and nothing more. Keeping the title of this post in mind, do you see any types whatsoever being expressed here? No, the only requirement for the Where method (when invoked &lt;em&gt;like&lt;/em&gt; an instance method on whatever e’s type is) is to take in something with a type compatible with “x =&amp;gt; f” where f’s type can be inferred of course because f is an expression. Notice how I said “&lt;em&gt;like &lt;/em&gt;an instance method”: the method call just follows the rules of method (overload) resolution, including – but not limited to – C# 3.0 extension methods when everything else fails. The only thing defined here is the type of f: the type of x can be anything (in most typical cases though it corresponds to the entity type from the fed in query expression in e) and the same holds for the return type of Where.&lt;/p&gt;  &lt;p&gt;Similarly, translation rules like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;&lt;em&gt;x &lt;/em&gt;&lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;em&gt;e &lt;/em&gt;&lt;font color="#0000ff"&gt;select &lt;/font&gt;&lt;em&gt;v&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;becomes&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;(&lt;em&gt;e&lt;/em&gt;).Select(&lt;em&gt;x&lt;/em&gt; =&amp;gt; &lt;em&gt;v&lt;/em&gt;)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;are equally flexible with regards to typing. From this point of view we could (and should) see LINQ as just another language pattern around certain methods, not necessarily related to a specific interface type (therefore establishing a sort of limited duck typing), just like &lt;em&gt;foreach &lt;/em&gt;only needs a “compatible GetEnumerator method” (see §8.8.4 of the C# 3.0 language specification, second step of the determination process during &lt;em&gt;foreach&lt;/em&gt;-compilation). Noteworthy is a counter-example where an interface type is required to use a specific language feature: the &lt;em&gt;using &lt;/em&gt;statement requires an &lt;em&gt;IDisposable&lt;/em&gt; object to operate on. The key takeaway though is that LINQ falls in the former category and just needs the right methods to translate away the query expression keywords.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;A different view on predicates&lt;/h1&gt;  &lt;p&gt;Let’s zoom in and investigate just one query operator: where. As we saw before it maps onto a Where method that takes in a lambda of the form x =&amp;gt; f. In here, x can be seen as an input element in the source sequence being processed, while f acts as the body of the predicate, establishing a filter condition. Although one could misuse the where operator to implement totally different semantics, we’ll assume we’re dealing with &lt;strong&gt;filtering&lt;/strong&gt; capabilities, i.e. an operator that restricts the returned elements from a given sequence based on some condition also known as a &lt;strong&gt;predicate&lt;/strong&gt;. As we discussed before, f shouldn’t necessarily be Boolean-typed, although the two common implementations – IEnumerable and IQueryable – define it as such:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;strong&gt;&lt;font color="#0000ff"&gt;bool&lt;/font&gt;&lt;/strong&gt;&amp;gt; predicate)         &lt;br /&gt;&lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;strong&gt;&lt;font color="#0000ff"&gt;bool&lt;/font&gt;&lt;/strong&gt;&amp;gt;&amp;gt; predicate)&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This means when using sources &lt;em&gt;e&lt;/em&gt; of any of the above types (ignoring a little caveat I’ll discuss below), the translation for the where operator:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from &lt;/font&gt;&lt;em&gt;x&lt;/em&gt; &lt;font color="#0000ff"&gt;in &lt;/font&gt;(&lt;em&gt;e&lt;/em&gt;).Where(&lt;em&gt;x&lt;/em&gt; =&amp;gt; &lt;em&gt;f&lt;/em&gt;) …&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;will bind x to T and f to bool, which gets enforced at compile-time (remember co- and contravariance rules for delegates, Func&amp;lt;T, bool&amp;gt; is just one of those). What’s the caveat I was hinting at? Well, first of all (incredibly obvious, I admit) is that this will only work if the Where extension method is brought in scope by means of the using keyword. LINQ doesn’t care about extension methods at all, but when the front-end language compiler rewrites the query expressions into chains of methods call, method resolution kicks in where extension methods are the fallback plan. That brings us to the real caveat: extension methods are only “fallbacks” and instance methods take precedence. Therefore instance methods have the capacity to “hide” extension methods with the same name and signature:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MyList&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Where(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; predicate)
    {
        …
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;T&amp;gt; GetEnumerator()
    {
        …
    }

    System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerator &lt;/span&gt;System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;.GetEnumerator()
    {
        …&lt;font color="#0000ff"&gt;&lt;br /&gt;&lt;/font&gt;    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;When using this class – even with System.Linq (and therefore the extension methods in System.Linq.Enumerable) in scope – you’ll see that our self-defined Where operator takes precedence:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_13.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="52" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_13.png" width="472" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;while another overload is still available through the extension methods:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_14.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="60" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_14.png" width="734" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This simple fact is easy to overlook but it’s incredibly important to leverage the full spectrum of possible LINQ provider implementations. Maybe you want all of the LINQ to Objects stuff to “just work” except for a few operators you want to implement yourself. Equally you could override IQueryable behavior when you wish to do so. Needless to say, the above just works fine with the &lt;em&gt;where&lt;/em&gt; keyword too. To prove this point, let’s use a simple breakpoint:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_15.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="237" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_15.png" width="743" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As you can see, while iterating over the resulting query, the highlighted lambda is being hit while being called from the MyList&amp;lt;string&amp;gt;.Where method. &lt;u&gt;Quiz:&lt;/u&gt; Would setting a breakpoint on “x” in Select reveal something in this particular case? Why (not)?&lt;/p&gt;

&lt;p&gt;In contrast, the projection lambda in &lt;em&gt;select&lt;/em&gt; will be called by an extension method on IEnumerable&amp;lt;T&amp;gt;. To illustrate this, I’ve tweaked the query a bit (why?) and disabled the “Just my code” feature in Visual Studio:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_16.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="375" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_16.png" width="644" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_17.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="239" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_17.png" width="767" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So how can we do even more creative stuff using this technique? What about doing this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MyList&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Where(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;&amp;gt; filter)
    {&lt;br /&gt;        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(T item &lt;span style="color:blue;"&gt;in this&lt;/span&gt;)
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(filter(item).Match(item.ToString()).Success)
                &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;item;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;T&amp;gt; GetEnumerator()
    {&lt;br /&gt;        …
    }

    System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerator &lt;/span&gt;System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;.GetEnumerator()
    {
        …
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Does this work? You bet :-). Actually we don’t even need to be IEnumerable&amp;lt;T&amp;gt;, but let’s keep that for later. Here’s how you can use it:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MyList&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt;() { &lt;span style="color:#a31515;"&gt;&amp;quot;abba&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;baab&amp;quot; &lt;/span&gt;} &lt;span style="color:blue;"&gt;where new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;^a.*a$&amp;quot;&lt;/span&gt;) &lt;span style="color:blue;"&gt;select &lt;/span&gt;x;

&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
    ;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This will only return abba in the foreach loop. Notice we’re actually doing nothing with the input of the “filter” function argument, but we could by referring to x in the &lt;em&gt;where &lt;/em&gt;clause. In this case, most likely we only want to process strings (as a regular expression operates on strings) and the regular expression won’t be variant based on the input. To make it a bit more concrete, here’s a sample of a dictionary:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt;
{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt; _lst = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt;();

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt; Where(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;&amp;gt; filter)
    {
        &lt;span style="color:#2b91af;"&gt;Regex &lt;/span&gt;predicate = filter(&lt;span style="color:blue;"&gt;null&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;string &lt;/span&gt;word &lt;span style="color:blue;"&gt;in &lt;/span&gt;_lst)
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(predicate.Match(word).Success)
                &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;word;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt; GetEnumerator()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_lst.GetEnumerator();
    }

    System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerator &lt;/span&gt;System.Collections.&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;.GetEnumerator()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_lst.GetEnumerator();
    }

    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Add(&lt;span style="color:blue;"&gt;string &lt;/span&gt;word)
    {
        _lst.Add(word);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Because we derive from IEnumerable&amp;lt;T&amp;gt;, we get all the LINQ to Objects operators for free, including the other Where overloads:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_18.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="44" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_18.png" width="428" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So now we can query our dictionary using a “regular” Boolean-valued predicate (with two distinct overloads: Func&amp;lt;string, bool&amp;gt; and Func&amp;lt;string, int, bool&amp;gt; where int represents the position in the original sequence), but also using a regular expression based predicate.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Taking it across the border: IQueryable (or something like it)&lt;/h1&gt;

&lt;p&gt;What&amp;#39; we’ve done before was just relying on local execution using IEnumerable’s LINQ to Objects extensions and some of our overrides and/or “query operator” overloads. In an equally simple manner we can make this work with remotable queries using IQueryable; the only difference would be in the signature of the Where operator. To scale things down a bit and avoid the burden of IQueryable’s “gang of three” properties, we’ll cook our own little query model that conforms with the LINQ query operators:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryService
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryQuery &lt;/span&gt;Where(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;&amp;gt;&amp;gt; filter)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryQuery&lt;/span&gt;(filter.Body);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The DictionaryService class acts as an entry-point to our service that’s capable of retrieving words based on regular expressions. It only supports a filtering operator, which will make it work together with LINQ. Notice we’re using an Expression&amp;lt;…&amp;gt; for the predicate so that we’ll get expression trees we can parse at runtime in order to perform some kind of remote execution. We’ll cook our own Regex class for reasons to be explained further on:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private string &lt;/span&gt;_regex;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;Regex(&lt;span style="color:blue;"&gt;string &lt;/span&gt;regex)
    {
        _regex = regex;
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex &lt;/span&gt;&lt;span style="color:blue;"&gt;operator&lt;/span&gt;&amp;amp;(&lt;span style="color:#2b91af;"&gt;Regex &lt;/span&gt;regex1, &lt;span style="color:#2b91af;"&gt;Regex &lt;/span&gt;regex2)
    {
        &lt;span style="color:green;"&gt;//
        // Just making the expression API happy to use Expression.And.
        //
        &lt;/span&gt;&lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotSupportedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Only for use in expression trees.&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Now we can turn our attention to the remaining DictionaryQuery class. The start is fairly simple:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryQuery&lt;/span&gt;
{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;_filter;

    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;DictionaryQuery(&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;filter)
    {
        _filter = filter;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryQuery &lt;/span&gt;Where(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;&amp;gt;&amp;gt; filter)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryQuery&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.And(_filter, filter.Body));
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt; GetEnumerator()
    {
        &lt;span style="color:blue;"&gt;string&lt;/span&gt;[] filters = Compile();
        &lt;span style="color:blue;"&gt;string&lt;/span&gt;[] results = GetWords(filters);
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;results.AsEnumerable().GetEnumerator();
    }&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Basically, a query consists of a filter that represents the aggregation of where filter clauses. This is stored in _filter. To allow for the user to specify multiple conditions, we have a Where operator available on the query object itself as well. All this operator does in this case is creating a new filter clause that “ands” together the original filter and the new filter. To do this, we just grab the passed in new filter’s body and hook it up with the original filter in a BinaryExpression of node type And. Notice we’re a bit lazy here and ideally we’d walk the tree of the passed in filter’s body to make sure it’s lambda parameter free (left as an exercise, tip: use a visitor). Expression.And will (statically) verify whether there’s an “And” (&amp;amp; in C# speak) operator available for use with the two specified arguments, hence we need our operator overload on Regex:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex &lt;/span&gt;&lt;span style="color:blue;"&gt;operator&lt;/span&gt;&amp;amp;(&lt;span style="color:#2b91af;"&gt;Regex &lt;/span&gt;regex1, &lt;span style="color:#2b91af;"&gt;Regex &lt;/span&gt;regex2)
{
    &lt;span style="color:green;"&gt;//
    // Just making the expression API happy to use Expression.And.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotSupportedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Only for use in expression trees.&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Notice this one is solely meant to be used in expression trees and doesn’t do anything useful. As a little exercise for the reader, what would it take to implement the &amp;amp;&amp;amp; operator (corresponds to AndAlso in expression trees)? What would be the implications concerning the semantics and the evaluation strategy on the target service? Can we map the semantics nicely and if so, how?&lt;/p&gt;

&lt;p&gt;The more important thing here though is the fact we’re implementing a GetEnumerator method. This will allow the user to iterate over the query results, which means we must translate the _filter into some service call to fetch results. This happens in a couple of stages: first we compile _filter into something the service understands (in this case just an array of strings) and next we send the compiled result (which we could cache if we want, so that subsequent iterations won’t trigger compilation again) to a service to process the request, getting the results back to iterate over. Question for the reader: why don’t we implement IEnumerable&amp;lt;string&amp;gt; here? Would it be desirable? Explain the pros and cons.&lt;/p&gt;

&lt;p&gt;Question remains how the compilation happens. Here it is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;private string&lt;/span&gt;[] Compile()
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;Compile(_filter).ToArray();
}

&lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt; Compile(&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;filter)
{
    &lt;span style="color:blue;"&gt;switch &lt;/span&gt;(filter.NodeType)
    {
        &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ExpressionType&lt;/span&gt;.And:
            {
                &lt;span style="color:#2b91af;"&gt;BinaryExpression &lt;/span&gt;binEx = (&lt;span style="color:#2b91af;"&gt;BinaryExpression&lt;/span&gt;)filter;
                &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;string &lt;/span&gt;regex &lt;span style="color:blue;"&gt;in &lt;/span&gt;Compile(binEx.Left).Concat(Compile(binEx.Right)))
                    &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;regex;
            }
            &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ExpressionType&lt;/span&gt;.New:
            {
                &lt;span style="color:#2b91af;"&gt;NewExpression &lt;/span&gt;newEx = (&lt;span style="color:#2b91af;"&gt;NewExpression&lt;/span&gt;)filter;
                &lt;span style="color:blue;"&gt;if &lt;/span&gt;(newEx.Type != &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;))
                    &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotSupportedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Invalid leaf node type in query: &amp;quot; &lt;/span&gt;+ newEx.Type);

                &lt;span style="color:green;"&gt;//
                // Only one constructor is public.
                //
                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;arg = newEx.Arguments[0];
                &lt;span style="color:blue;"&gt;if &lt;/span&gt;(arg.NodeType != &lt;span style="color:#2b91af;"&gt;ExpressionType&lt;/span&gt;.Constant)
                    &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotSupportedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Regex constructor uses in query should have a constant argument value.&amp;quot;&lt;/span&gt;);

                &lt;span style="color:#2b91af;"&gt;ConstantExpression &lt;/span&gt;constEx = (&lt;span style="color:#2b91af;"&gt;ConstantExpression&lt;/span&gt;)arg;
                &lt;span style="color:blue;"&gt;string &lt;/span&gt;value = (&lt;span style="color:blue;"&gt;string&lt;/span&gt;)constEx.Value;
                &lt;span style="color:blue;"&gt;if &lt;/span&gt;(value == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
                    &lt;span style="color:blue;"&gt;yield break&lt;/span&gt;;
                &lt;span style="color:blue;"&gt;else
                    yield return &lt;/span&gt;value;
            }
            &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;default&lt;/span&gt;:
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotSupportedException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Invalid expression type in query: &amp;quot; &lt;/span&gt;+ filter.NodeType);
    }                
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This is fairly straightforward as well. We just expect two types of nodes: BinaryExpression nodes of type And used as the query composition operator, and NewExpression nodes for the leaf nodes (although leaf isn’t strictly true, why?) representing the atoms of the query predicate. Most code is boilerplate error checking but the points of interest are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The use of iterators to produce a stream of strings representing the individual regular expressions. Notice the use of recursion in the And case (unfortunately we don’t have a &lt;em&gt;yield foreach&lt;/em&gt; construct yet). &lt;/li&gt;

  &lt;li&gt;How we get the the value of the regular expression on the leaf nodes, through the first argument on the constructor. Actually, we don’t even need the private field in Regex in this case as we’re purely using it for expression trees and we can get to it through the constructor’s first argument in the expression tree. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;To show what the tree looks like so far, consider the following query:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;dict = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryService&lt;/span&gt;();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;word &lt;span style="color:blue;"&gt;in &lt;/span&gt;dict
          &lt;span style="color:blue;"&gt;where new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;^A.*a$&amp;quot;&lt;/span&gt;)
          &lt;span style="color:blue;"&gt;where new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;.*m.*&amp;quot;&lt;/span&gt;)
          &lt;span style="color:blue;"&gt;select &lt;/span&gt;word;

&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
    ;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Setting a breakpoint on Compile allows us to inspect the filter:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_19.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="74" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_19.png" width="547" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we just see the ToString representation but when clicking the magnifier glass (assuming the Expression Tree Visualizer sample is installed), we get to see the entire tree:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_20.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="580" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_20.png" width="600" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice where our information of interest lives and how our expression tree compiler extracts it carefully from the tree. Another little quiz for the reader: is the query below equivalent to the one above (watch out for details)? Why (not)?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;dict = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryService&lt;/span&gt;();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;word &lt;span style="color:blue;"&gt;in &lt;/span&gt;dict
          &lt;span style="color:blue;"&gt;where new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;^A.*a$&amp;quot;&lt;/span&gt;) &amp;amp;&amp;amp; &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;.*m.*&amp;quot;&lt;/span&gt;)
          &lt;span style="color:blue;"&gt;select &lt;/span&gt;word;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Last but not least we should take a look at our service itself. Obviously you could imagine any real service technology being used, such as WCF, but let’s stick with some simple fake local execution:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;private string&lt;/span&gt;[] GetWords(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] regexs)
{
    &lt;span style="color:green;"&gt;//
    // This acts as an imaginary remote service.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;conditions = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;System.Text.RegularExpressions.&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;&amp;gt;();
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;string &lt;/span&gt;regex &lt;span style="color:blue;"&gt;in &lt;/span&gt;regexs)
        conditions.Add(&lt;span style="color:blue;"&gt;new &lt;/span&gt;System.Text.RegularExpressions.&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(regex));

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;a &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AppDomain&lt;/span&gt;.CurrentDomain.GetAssemblies()
              &lt;span style="color:blue;"&gt;from &lt;/span&gt;t &lt;span style="color:blue;"&gt;in &lt;/span&gt;a.GetTypes()
              &lt;span style="color:blue;"&gt;from &lt;/span&gt;m &lt;span style="color:blue;"&gt;in &lt;/span&gt;t.GetMethods()
              &lt;span style="color:blue;"&gt;let &lt;/span&gt;word = m.Name
              &lt;span style="color:blue;"&gt;where &lt;/span&gt;conditions.All(r =&amp;gt; r.Match(word).Success)
              &lt;span style="color:blue;"&gt;select &lt;/span&gt;word;

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;res.ToArray();
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The biggest source of in-memory data is without doubt reflection, so let’s use it :-). Here we’re using real regular expressions (Questions: Why did we wrap them in the first place? Could we use some serialization mechanism? Explain!) to do the matching as part of a LINQ query (regular LINQ to Objects this time – it would be interesting to use our “LINQ-by-Regex” implementation recursively :-)). Notice how we return an array which has implications for the laziness when consuming data. Depending on the transport protocol the implementation could be streaming data to the client, so that the client can terminate the request at any point in time (when breaking from the foreach loop for instance). Or we could implement some kind of paging to retrieve the results in batches.&lt;/p&gt;

&lt;p&gt;On my computer the following query:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;dict = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DictionaryService&lt;/span&gt;();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;word &lt;span style="color:blue;"&gt;in &lt;/span&gt;dict
          &lt;span style="color:blue;"&gt;where new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;^A.*a$&amp;quot;&lt;/span&gt;)
          &lt;span style="color:blue;"&gt;where new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;.*m.*&amp;quot;&lt;/span&gt;)
          &lt;span style="color:blue;"&gt;select &lt;/span&gt;word;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;returns&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&amp;quot;&lt;strong&gt;A&lt;/strong&gt;utoIncre&lt;strong&gt;m&lt;/strong&gt;entCannotSetIfHasDat&lt;strong&gt;a&lt;/strong&gt;&amp;quot; 

    &lt;br /&gt;&amp;quot;&lt;strong&gt;A&lt;/strong&gt;ddSche&lt;strong&gt;ma&lt;/strong&gt;&amp;quot;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;when running it in the context of a Windows Forms application created with Visual Studio 2008.&lt;/p&gt;

&lt;p&gt;Exercise: Think of ways to simplify this regular-expression based (remote!) querying capability, especially with regards to the end-user writing queries targeting it. Can we get rid of the “Regex” word in there? Why (not)? How could we compile other Boolean operators to compose more complex queries and send them across to the server (tip: *fix).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Staged migration of query languages&lt;/h1&gt;

&lt;p&gt;By now you might wonder where we can use this “Frankenstein” LINQ flavor where we party on the existing language integration but extend it with our own predicate types, or projection types (remember the return type of Select can be anything as well), or … types. As illustrated above, in some cases you could imagine other predicate-like types like regular expressions to be applicable and we can glue them in with the &lt;em&gt;where &lt;/em&gt;keyword in a fairly straightforward manner. However, there are other cases where this becomes extremely useful as well: dealing with “(old) dragon” query languages that either do not map nicely on LINQ operators or that are loaded with huge existing investments from users in terms of existing query definitions and/or models.&lt;/p&gt;

&lt;p&gt;Let’s start by exploring the former. A typical sample of mismatches especially (when dealing with predicates) occurs for “exotic operators” or operators that have very specific semantics in a target language that are not available in VB or C#. A few samples:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;LDAP has an “approximately equal to” ~= operator. &lt;/li&gt;

  &lt;li&gt;CAML has a DateRangesOverlap method to operate on calendars and such. &lt;/li&gt;

  &lt;li&gt;SQL has various date/time operators that are not in the BCL with identical enough semantics. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To address this, one typically creates static helper methods to act as “legacy predicate islands” in a LINQ query. For example, LINQ to SQL has the SqlMethods class:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_21.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="196" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_21.png" width="209" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;which contains a “Like” operator that allows people to re-use their existing “LIKE” operator clauses from SQL directly in LINQ to SQL:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_22.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="75" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_22.png" width="392" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Attempting to cross-compile .NET regular expressions to an equivalent SQL predicate would be fairly interesting to say the least :-), so escape valves like those are ideal to address this mismatch. Methods like those simply act as stubs for use in expression tree translation and can’t be used on the client:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_23.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="282" alt="image" src="http://www.bartdesmet.info/images_wlw/WhoeversaidpredicatesneedtobeBooleanvalu_14E7E/image_thumb_23.png" width="814" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The nice thing about this is that you can still get some decent degree of type-verification when writing LINQ queries: Like takes in two strings and the compiler will enforce this. Of course, what’s inside the “pattern” parameter won’t be subject to checking as it’s impossible and undesirable to extend the front-end language compilers with query domain-specific knowledge to interpret “LIKE” strings and such (much like “printf” strings, although some compilers allow to verify those, but that’s a different topic of discussion).&lt;/p&gt;

&lt;p&gt;Another place where the use of customized LINQ operators can be handy is when dealing with old APIs to allow to do querying while you want to put some LINQ sugar on top of it. For example, you might have a widely-used API to model queries for your specific data store. E.g. &lt;a href="http://www.codeplex.com/camldotnet"&gt;CAML.NET&lt;/a&gt; provides an object model to write CAML predicates (and more). What if people have already invested in such an API and have written huge queries encoded in terms of such an API? Or maybe you &lt;u&gt;need&lt;/u&gt; such an object model because there’s no nice O/&amp;lt;whatever DSQL&amp;gt; mapping available. Well, first of all the question becomes where you still want to use LINQ. If there’s no benefit at all (such as strong typing all the way through or a nice object mapping) the advantages are slim. However, when an object mapping (and hence some degree of strong typing) is still possible but certain parts of a query already have specialized APIs (e.g. a predicate API) LINQ might still be of interest. Let’s give a sample with CAML.NET:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;product &lt;span style="color:blue;"&gt;in &lt;/span&gt;ctx.Products
          &lt;span style="color:blue;"&gt;where &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;CAML&lt;/span&gt;.And(
                    &lt;span style="color:#2b91af;"&gt;CAML&lt;/span&gt;.Gt(
                        &lt;span style="color:#2b91af;"&gt;CAML&lt;/span&gt;.FieldRef(&lt;span style="color:#a31515;"&gt;&amp;quot;UnitPrice&amp;quot;&lt;/span&gt;),
                        &lt;span style="color:#2b91af;"&gt;CAML&lt;/span&gt;.Value(123)
                    ),
                    &lt;span style="color:#2b91af;"&gt;CAML&lt;/span&gt;.BeginsWith(
                        &lt;span style="color:#2b91af;"&gt;CAML&lt;/span&gt;.FieldRef(&lt;span style="color:#a31515;"&gt;&amp;quot;ProductName&amp;quot;&lt;/span&gt;),
                        &lt;span style="color:#2b91af;"&gt;CAML&lt;/span&gt;.Value(&lt;span style="color:#a31515;"&gt;&amp;quot;C&amp;quot;&lt;/span&gt;)
                    )
                )
          &lt;span style="color:blue;"&gt;select &lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;{ Name = product.ProductName, Price = p.UnitPrice };&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The reader is invited to infer the signature of the Where method used here. Similarly, the same could be expressed in terms of plain XML:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;product &lt;span style="color:blue;"&gt;in &lt;/span&gt;ctx.Products
          &lt;span style="color:blue;"&gt;where new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;And&amp;quot;&lt;/span&gt;,
                    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Gt&amp;quot;&lt;/span&gt;,      
                        &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;FieldRef&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XAttribute&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;UnitPrice&amp;quot;&lt;/span&gt;)),
                        &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XAttribute&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Type&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;Integer&amp;quot;&lt;/span&gt;), 123)
                    ),
                    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;BeginsWith&amp;quot;&lt;/span&gt;,      
                        &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;FieldRef&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XAttribute&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;ProductName&amp;quot;&lt;/span&gt;)),
                        &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XAttribute&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Type&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;String&amp;quot;&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;C&amp;quot;&lt;/span&gt;)
                    )
                )
          &lt;span style="color:blue;"&gt;select new &lt;/span&gt;{ Name = product.ProductName, Price = p.UnitPrice };&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;or even better in VB:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;Dim &lt;/span&gt;res = &lt;span style="color:blue;"&gt;From &lt;/span&gt;product &lt;span style="color:blue;"&gt;In &lt;/span&gt;ctx.Products _
          &lt;span style="color:blue;"&gt;Where &lt;/span&gt;(&lt;span style="color:#6464b9;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#844646;"&gt;And&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;
                     &amp;lt;&lt;/span&gt;&lt;span style="color:#844646;"&gt;Gt&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;
                         &amp;lt;&lt;/span&gt;&lt;span style="color:#844646;"&gt;FieldRef &lt;/span&gt;&lt;span style="color:#b96464;"&gt;Name&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;=&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;UnitPrice&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;/&amp;gt;
                         &amp;lt;&lt;/span&gt;&lt;span style="color:#844646;"&gt;Value &lt;/span&gt;&lt;span style="color:#b96464;"&gt;Type&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;=&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;Integer&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:#555555;"&gt;123&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:#844646;"&gt;Value&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;
                     &amp;lt;/&lt;/span&gt;&lt;span style="color:#844646;"&gt;Gt&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;
                     &amp;lt;&lt;/span&gt;&lt;span style="color:#844646;"&gt;BeginsWith&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;
                         &amp;lt;&lt;/span&gt;&lt;span style="color:#844646;"&gt;FieldRef &lt;/span&gt;&lt;span style="color:#b96464;"&gt;Name&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;=&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;ProductName&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;/&amp;gt;
                         &amp;lt;&lt;/span&gt;&lt;span style="color:#844646;"&gt;Value &lt;/span&gt;&lt;span style="color:#b96464;"&gt;Type&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;=&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;String&lt;/span&gt;&lt;span style="color:#555555;"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:#555555;"&gt;C&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:#844646;"&gt;Value&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;
                     &amp;lt;/&lt;/span&gt;&lt;span style="color:#844646;"&gt;BeginsWith&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;
                 &amp;lt;/&lt;/span&gt;&lt;span style="color:#844646;"&gt;And&lt;/span&gt;&lt;span style="color:#6464b9;"&gt;&amp;gt;&lt;/span&gt;) _
          &lt;span style="color:blue;"&gt;Select New With &lt;/span&gt;{.Name = product.ProductName, .Price = product.UnitPrice }&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Notice we still have the richness of the projection in terms of object construction, so there’s still a benefit although the Where part is a black hole without compile-time type checking. However, given the context and the generated mappings the expression compiler that would need to be implemented could do some more intelligent analysis of the query before attempting to execute it remotely. Also notice it’s perfectly possible to combine approaches: you could have various overloads to support different mechanisms to express the same predicate (or projection, or sorting, or grouping, or …). There could even be a mixed approach within a clause:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;product &lt;span style="color:blue;"&gt;in &lt;/span&gt;ctx.Products
          &lt;span style="color:blue;"&gt;where &lt;font color="#000000"&gt;product.UnitPrice &amp;gt; 123&lt;br /&gt;                &amp;amp;&amp;amp; &lt;strong&gt;???(&lt;/strong&gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;BeginsWith&amp;quot;&lt;/span&gt;,      
                        &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;FieldRef&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XAttribute&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;ProductName&amp;quot;&lt;/span&gt;)),
                        &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XElement&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;XAttribute&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Type&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;String&amp;quot;&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;S&amp;quot;&lt;/span&gt;)
                   )&lt;strong&gt;)&lt;/strong&gt;
          &lt;span style="color:blue;"&gt;select &lt;/span&gt;product.Name;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;I’ll leave it to the creative reader to fill out the ???(…) part in here and to explain why this mysterious thing would be required.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;LINQ is an incredibly extensible and flexible beast. Writing APIs that are LINQ-aware can be done in a whole spectrum of styles, of which I’m just listing a few discrete flavors below:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Do nothing &lt;/strong&gt;– The simplest approach, just use LINQ to Objects and such. Maybe your API can be expressed in terms of IEnumerable&amp;lt;T&amp;gt; and you’re done with it. 

    &lt;br /&gt;&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Stand in the shadow of giants – &lt;/strong&gt;LINQ to Objects is a giant – it knows of all the standard query operators, and making your API work with IEnumerable&amp;lt;T&amp;gt; is the only thing it takes to leverage LINQ to Objects. That’s exactly what LINQ to XML does in terms of exposing XML in more intelligent fashion than “imperative-style&amp;quot; DOM programming. Other samples of this approach include the use of LINQ to SQL when your target database has a “SQL bridge” provider (e.g. an OLE DB provider for AD), although LINQ to SQL is intrinsically aware about Microsoft SQL Server 2000/2005. 

    &lt;br /&gt;&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Follow the troups&lt;/strong&gt; – The other extreme, do what lots of people do for fun and profit: implement your own IQueryable&amp;lt;T&amp;gt;. This might be overkill in quite some cases as you buy in to all of the query operators and most likely the query language being targeted does not support even half of them. There’s no magic threshold indicating when to consider IQueryable&amp;lt;T&amp;gt; but if you only want to do Where and Select most likely this approach doesn’t scale all that well. 

    &lt;br /&gt;&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Embrace and extend – &lt;/strong&gt;You’re happy with LINQ to objects, your object is IEnumerable&amp;lt;T&amp;gt; but you’d like another way to filter/project/order/group/join stuff. To solve this equation, you can add overloads for the query operators as instance level methods on your class. It will just work with the built-in LINQ syntax. This technique can also be used if you’ve implemented a full IQueryable&amp;lt;T&amp;gt; and did not run out of juice yet, so you want to add even more query operators (for which you obviously won’t get any LIN in LINQ). 

    &lt;br /&gt;&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Override and overrule – &lt;/strong&gt;Hijack the existing LINQ implementation by “overriding” or “hiding” existing LINQ extension methods. The only thing you need to do is provide an instance level method with the same signature as the operator you want to override. 

    &lt;br /&gt;&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Cook it yourself – &lt;/strong&gt;This is the most creative approach I’m often referring to as “LINQ to Simpsons”. As soon as you provide the right set of methods, the VB and C# compilers will be perfectly happy to translate the query expressions into underlying method calls for you. To illustrate this: guess the type of the query below. More information can be found in my &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/04/27/q-is-iqueryable-the-right-choice-for-me.aspx"&gt;Q: Is IQueryable the Right Choice for Me?&lt;/a&gt; post as well. 

    &lt;br /&gt;

    &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = (&lt;font color="#0000ff"&gt;from &lt;/font&gt;x &lt;font color="#0000ff"&gt;in new &lt;/font&gt;&lt;font color="#008080"&gt;Homer&lt;/font&gt;() &lt;font color="#0000ff"&gt;where &lt;/font&gt;x.HasSkateboard &lt;font color="#0000ff"&gt;select &lt;/font&gt;x.Sister).Father 

    &lt;br /&gt;

    &lt;br /&gt;where 

    &lt;br /&gt;

    &lt;br /&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Homer&lt;/font&gt; 

    &lt;br /&gt;{ 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Marge &lt;/font&gt;Where(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Bart&lt;/font&gt;, &lt;font color="#0000ff"&gt;bool&lt;/font&gt;&amp;gt; p) { … } 

    &lt;br /&gt;} 

    &lt;br /&gt;

    &lt;br /&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;Marge 

    &lt;br /&gt;{ 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Homer &lt;/font&gt;Select(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Maggie&lt;/font&gt;, &lt;font color="#008080"&gt;Lisa&lt;/font&gt;&amp;gt; p) { … } 

    &lt;br /&gt;} &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13970" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/VB+9.0/default.aspx">VB 9.0</category></item><item><title>C# 3.0 Query Expression Translation Cheat Sheet</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/30/c-3-0-query-expression-translation-cheat-sheet.aspx</link><pubDate>Sat, 30 Aug 2008 08:29:05 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13937</guid><dc:creator>bart</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13937</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/30/c-3-0-query-expression-translation-cheat-sheet.aspx#comments</comments><description>&lt;p&gt;As a reference for some planned and unplanned future posts, I wanted to share out my “cheat sheet” for the C# 3.0 translation carried out for query expressions. Obviously it’s based on the &lt;a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc"&gt;C# 3.0 Language Specification&lt;/a&gt; more specially section 7.15.2. A few remarks that deserve more attention when reading the specification:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Words in &lt;strong&gt;bold&lt;/strong&gt; are &lt;em&gt;contextual &lt;/em&gt;keywords; these are &lt;u&gt;not&lt;/u&gt; reserved keywords as the language doesn’t introduce new reserved keywords to ensure forward compatibility for programs written in previous language versions (e.g. “from” could be used as a variable name).&lt;/li&gt;    &lt;li&gt;Method names indicated in &lt;font color="#ff0000"&gt;red&lt;/font&gt; are the query operators known by the compiler as compilation targets for the corresponding query syntax &lt;em&gt;contextual &lt;/em&gt;keywords. Where these methods come from is purely a question answered by method resolution rules, obviously including extension methods from C# 3.0 on.&lt;/li&gt;    &lt;li&gt;The ‘*’ in the translations below stands for the transparent identifier, more of an implementation aspect of the compiler to “carry forward” the range variables captured in the anonymous type produced by a query operation (e.g. in SelectMany). This illustrates that anonymous types (as well as lambda BLOCKED EXPRESSION are essential pieces of glue to make LINQ work (although alternatives based on a hypothetical “tuple type” runtime feature would work too).&lt;/li&gt;    &lt;li&gt;For the orderby operator, corresponding flavors with descending order have been omitted. Essentially all of the ordering clauses can optionally have the descending keyword, resulting in an OrderByDescending or ThenByDescending call in the corresponding translation.&lt;/li&gt;    &lt;li&gt;All the rules are mutually recursive: starting with a query expression, the translation will gradually “compile away” certain parts of the query expression syntax into method call driven equivalent expressions. Notice all rules without an ellipsis … on the left-hand side don’t have any query expression keywords left on the right-hand side – these are the terminal “closed” expressions that are entirely expressible in C# 3.0 \ { LINQ }. It’s like peeling off the LINQ layer from the C# 3.0 onion.&lt;/li&gt;    &lt;li&gt;The first two rules for Select seem redundant, i.e. when substituting v for x in the second rule one gets the first rule. The reason they are spelled out each individually is because the first rule covers degenerate expressions (covered in &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/20/what-do-vb-9-0-error-bc36593-expression-of-type-x-is-not-queryable-and-c-3-0-error-cs1936-could-not-find-an-implementation-of-the-query-pattern-for-source-type-x-really-mean.aspx"&gt;another post&lt;/a&gt; of mine) and rules should be evaluated from top to bottom. The Select ( x =&amp;gt; x ) is kept based on the conditions spelled out in section 7.15.2.3.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So here’s my cheat sheet:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/C3.0QueryExpressionTranslationCheatSheet_14DA/image.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="863" alt="image" src="http://www.bartdesmet.info/images_wlw/C3.0QueryExpressionTranslationCheatSheet_14DA/image_thumb.png" width="1178" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Feel free to redistribute it in any form but I’d appreciate at least a reference to the official &lt;a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc"&gt;C# 3.0 Language Specification&lt;/a&gt; with it as that’s the ultimate resource for the detailed language specifics. A pointer to my blog would be much appreciated as well of course :-).&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13937" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>What Do VB 9.0 Error “BC36593: Expression of type ‘X’ is not queryable.” And C# 3.0 Error “CS1936: Could not find an implementation of the query pattern for source type ‘X’.” Really Mean?</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/20/what-do-vb-9-0-error-bc36593-expression-of-type-x-is-not-queryable-and-c-3-0-error-cs1936-could-not-find-an-implementation-of-the-query-pattern-for-source-type-x-really-mean.aspx</link><pubDate>Thu, 21 Aug 2008 03:04:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13881</guid><dc:creator>bart</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13881</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/20/what-do-vb-9-0-error-bc36593-expression-of-type-x-is-not-queryable-and-c-3-0-error-cs1936-could-not-find-an-implementation-of-the-query-pattern-for-source-type-x-really-mean.aspx#comments</comments><description>&lt;p&gt;While preparing for another one of my posts, soon to be published, I received the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WhatDoVB9.0ErrorBC36593Expres.ReallyMean_1481C/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="208" alt="image" src="http://bartdesmet.info/images_wlw/WhatDoVB9.0ErrorBC36593Expres.ReallyMean_1481C/image_thumb.png" width="677" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What can one do when observing such a message? Since watching a grown man cry is both a pathetic and embarrassing situation, &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=39DE1DD0-F775-40BF-A191-09F5A95EF500&amp;amp;displaylang=en"&gt;downloading the language specification&lt;/a&gt; is a good start. Here are my findings. Section 11.21 on Query Expressions says:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;A query expression is an expression that applies a series of query operators to the elements of a &lt;u&gt;queryable collection&lt;/u&gt;.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Query operators are what I’m playing with – as will become apparent later on – but what’s supposed to be a “queryable collection”? Somewhere further, in paragraph 11.21.2 on Queryable Types the following is said:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;Query expressions are implemented by translating the expression into calls to well-known methods on a &lt;u&gt;collection type&lt;/u&gt;. These well-defined methods define the element type of the &lt;u&gt;queryable collection&lt;/u&gt; as well as the result types of query operators executed on the collection. Each query operator specifies the method or methods that the query operator is generally translated into, although the specific translation is implementation dependent.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Right, but what makes up a &lt;strong&gt;“queryable collection”&lt;/strong&gt;? Where not getting closer yet but somewhere further in the same paragraph one can make a little jump in the air to express a joyful mood:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;A queryable collection type must satisfy one of the following conditions, in order of preference:&lt;/em&gt;&lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;&lt;em&gt;It must define a conforming Select method.&lt;/em&gt; &lt;/li&gt;      &lt;li&gt;&lt;em&gt;It must have have one of the following methods          &lt;br /&gt;          &lt;br /&gt;&lt;font color="#0000ff"&gt;Function&lt;/font&gt; AsEnumerable() &lt;font color="#0000ff"&gt;As &lt;/font&gt;CT           &lt;br /&gt;&lt;font color="#0000ff"&gt;Function&lt;/font&gt; AsQueryable() &lt;font color="#0000ff"&gt;As &lt;/font&gt;CT           &lt;br /&gt;          &lt;br /&gt;which can be called to obtain a queryable collection. If both methods are provided, AsQueryable is preferred over AsEnumerable.           &lt;br /&gt;&lt;/em&gt;&lt;/li&gt;      &lt;li&gt;&lt;em&gt;It must have a method          &lt;br /&gt;          &lt;br /&gt;&lt;font color="#0000ff"&gt;Function &lt;/font&gt;Cast(&lt;font color="#0000ff"&gt;Of &lt;/font&gt;T)() &lt;font color="#0000ff"&gt;As &lt;/font&gt;CT           &lt;br /&gt;          &lt;br /&gt;which can be called with the type of the range variable to produce a queryable collection.&lt;/em&gt; &lt;/li&gt;   &lt;/ul&gt; &lt;/blockquote&gt;  &lt;p&gt;In here CT stands for a (queryable) collection with elements of type T. The definition is actually recursive: one of the three bullets needs to be satisfied in order for something to be “queryable CT”. It’s clear that the latter two act as (the recursive case) escape valves to turn something “non-queryable” into something queryable because their result type is denoted as CT. So, all the power lies ultimately in the first bullet (the base case) on a “conforming Select method”. A bit further in the paragraph we read:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;It is not necessary for a collection object to implement all of the methods needed by all the query operators, although every collection object must at least support the Select query operator.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Why this restriction? The VB 9.0 spec doesn’t really tell but actually C# does have a similar rule, which is more explanatory. In the &lt;a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc"&gt;C# 3.0 Specification&lt;/a&gt; there’s a paragraph 7.15.2.3 on so-called &lt;strong&gt;“Degenerate query expressions”&lt;/strong&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;A degenerate query expression is one that trivially selects the elements of the source. (…) It is important (…) to ensure that the result of a query expression is never the source object itself, as that would reveal the type and identity of the source to the client of the query. Therefore this step protected degenerate queries written directly in source code by explicitly calling Select on the source. (…)&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;In other words, something like&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;from&lt;/font&gt; c &lt;font color="#0000ff"&gt;in &lt;/font&gt;customers &lt;font color="#0000ff"&gt;select &lt;/font&gt;s&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;translates into&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;customers.Select(c =&amp;gt; c)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;which looks as unnecessary (in the end the lambda passed in is the identity function) but it makes sure that a query can never degenerate in its original source, which ensures the source is kept hidden (some form of encapsulation if you want) from the query consumer. Indeed, the paragraph continues:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;It is then up to the implementers of Select and other query operators to ensure that these methods never return the source object itself.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Let’s turn it into practice. Assume we have the following class definitions:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Foo &lt;/font&gt;Where(&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;object&lt;/font&gt;, &lt;font color="#0000ff"&gt;bool&lt;/font&gt;&amp;gt; predicate)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {       &lt;br /&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // …&lt;/font&gt;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;}       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Foo&lt;/font&gt;       &lt;br /&gt;{       &lt;br /&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; // …        &lt;br /&gt;&lt;/font&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;then the following query would translate fine:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;b &lt;font color="#0000ff"&gt;in new &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;() &lt;font color="#0000ff"&gt;where true select &lt;/font&gt;b;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;which strictly speaking translates into&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;().Where(b =&amp;gt; &lt;font color="#0000ff"&gt;true&lt;/font&gt;).Select(b =&amp;gt; b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;but Where already “hides” the original source, so the degenerate Select can be trimmed away:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;().Where(b =&amp;gt; &lt;font color="#0000ff"&gt;true&lt;/font&gt;);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;The fact the result of b.Where, an instance of Foo, doesn’t have a Select method won’t bit us in this case (notice that Where(b =&amp;gt; true) could be treated as a degenerate case as well; however, the compiler doesn’t treat it that way and leaves the Where call in). However, when the query is the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;b &lt;font color="#0000ff"&gt;in new &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;() &lt;font color="#0000ff"&gt;select &lt;/font&gt;b;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;the translation would look like&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;().Select(b =&amp;gt; b)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Dropping Select would make the result equal to the source, which is a violation of the rules in 7.15.2.3, so the compiler complains about the non-existence of Select on class Bar (trivial question: why not on Foo this time?) in this case:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WhatDoVB9.0ErrorBC36593Expres.ReallyMean_1481C/image_3.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="208" alt="image" src="http://bartdesmet.info/images_wlw/WhatDoVB9.0ErrorBC36593Expres.ReallyMean_1481C/image_thumb_3.png" width="677" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So, implementing Select is a bare minimum for query provider implementations (that do not go through IQueryable&amp;lt;T&amp;gt; because those already “inherit” a Select implementation). Here’s the resulting code in VB:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;Module &lt;/font&gt;&lt;font color="#008080"&gt;W&lt;/font&gt;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;Sub &lt;/font&gt;Main       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;Dim &lt;/font&gt;res = &lt;font color="#0000ff"&gt;From &lt;/font&gt;b &lt;font color="#0000ff"&gt;In New &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt; &lt;font color="#0000ff"&gt;Where True&lt;/font&gt;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;End Sub&lt;/font&gt;       &lt;br /&gt;&lt;font color="#0000ff"&gt;End Module &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font color="#0000ff"&gt;Class &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;Public Function &lt;/font&gt;Where(p &lt;font color="#0000ff"&gt;As &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;(&lt;font color="#0000ff"&gt;Of Object&lt;/font&gt;, &lt;font color="#0000ff"&gt;Boolean&lt;/font&gt;)) &lt;font color="#0000ff"&gt;As &lt;/font&gt;&lt;font color="#008080"&gt;Foo&lt;/font&gt;       &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Return Nothing        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; End Function&lt;/font&gt;       &lt;br /&gt;      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;Public Function &lt;/font&gt;[Select](s &lt;font color="#0000ff"&gt;As &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;(&lt;font color="#0000ff"&gt;Of Object&lt;/font&gt;, &lt;font color="#0000ff"&gt;Object&lt;/font&gt;)) &lt;font color="#0000ff"&gt;As &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;       &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Return Nothing        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; End Function&lt;/font&gt;       &lt;br /&gt;&lt;font color="#0000ff"&gt;End Class &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font color="#0000ff"&gt;Class &lt;/font&gt;&lt;font color="#008080"&gt;Foo&lt;/font&gt;       &lt;br /&gt;&lt;font color="#0000ff"&gt;End Class&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;that makes the compiler happy. Notice VB doesn’t require you to say “Select b”, a little but handy feature although it makes degenerate queries even more hidden. Why? Tell me what the following means:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;Dim &lt;/font&gt;res = &lt;font color="#0000ff"&gt;From &lt;/font&gt;b &lt;font color="#0000ff"&gt;In New &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Indeed, the compiler will insert a Select method call for you (hence the reason it needs a Select method in order to be able to do this):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WhatDoVB9.0ErrorBC36593Expres.ReallyMean_1481C/image_4.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="331" alt="image" src="http://bartdesmet.info/images_wlw/WhatDoVB9.0ErrorBC36593Expres.ReallyMean_1481C/image_thumb_4.png" width="854" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where the referenced lambda is as trivial as you can imagine.&lt;/p&gt;  &lt;p&gt;Conclusion: We don’t allow degenerate queries to occur; both compiler errors are manifestations of that rule. Obviously this relies on a trust relationship with query providers to play according to the rules; those should never return the original query source when applying a query on it, even if that query just selects all elements from the source. Why? The source object may contain things such as connection strings that you don’t want to leak across the border established by a query over that source object. Providers like LINQ to Objects (returns an iterator yielding all elements in the input source when presented with a degenerate select), LINQ to SQL (establishes some Query&amp;lt;T&amp;gt; object over a Table&amp;lt;T&amp;gt; even when presented with a degenerate select) and LINQ to XML (which is just LINQ to Objects with a special API powering it) play according to those rules.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13881" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/VB+9.0/default.aspx">VB 9.0</category></item><item><title>The Most Funny Interface Of The Year … IQueryable&lt;T&gt;</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/15/the-most-funny-interface-of-the-year-iqueryable-lt-t-gt.aspx</link><pubDate>Sat, 16 Aug 2008 05:43:08 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13863</guid><dc:creator>bart</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13863</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/15/the-most-funny-interface-of-the-year-iqueryable-lt-t-gt.aspx#comments</comments><description>&lt;p&gt;Recently I delivered a talk at TechEd South Africa on “Custom LINQ Providers”. This is a very broad topic to cover in barely 60 minutes especially if one has to explain pretty “abstract” pieces of art like IQueryable&amp;lt;T&amp;gt;. Apparently I managed to do so looking at the scores &amp;lt;g&amp;gt;. But why is IQueryable&amp;lt;T&amp;gt; such a special specimen? This post will explain why.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h1&gt;What’s in a name?&lt;/h1&gt;  &lt;p&gt;Well, not that much: I and Queryable. “I” means there’s work to do if you want to use it – that’s precisely what interfaces are all about (the Imperative form of to Implement). “Queryable” is the promise of the interface – what we’ll get in return for the “I” labor.&lt;/p&gt;  &lt;p&gt;So, what would you guess that needs to be implemented to get query capabilities in return? A blind guess would be: every query operator? Looking at all of the query operators we support with all their fancy overloads, that would mean 126 methods. Framework designers are sometimes masochistic but to such a large extent? Nah! There’s a magic threshold for interfaces which I would conservatively set to 10 methods. If you go beyond that threshold, only masochistic framework users will care to (try to) implement your interface. People have come up with brilliant (hmm) ideas to reduce the burden of interface implementation by trading the problem for another set of problems: abstract base classes. Right, we only have 47 distinct query operators and additional overloads can do with a default implementation in quite some cases, but still 47 abstract methods is way too much especially if most implementors will only be interested in a few of them, so you get a sparse minestrone soup with floating NotImplementedExceptions everywhere. And you’re facing the restrictions of the runtime with respect to single inheritance only, which is one of the reasons I don’t believe that much in abstract base classes as extensibility points (although there are cases where these work great).&lt;/p&gt;  &lt;p&gt;We need something better. What about the silver bullet (hmm) to all complexity problems: refactoring? Oh yeah, we could have 47 interfaces each with a few methods (all having the same name since they would be overloads) with exciting names like IWhereable, ISelectable, IOrderable, IGroupable, etc. If it doesn’t scale against one axis, what about pivoting the whole problem and make it again not scale against the orthogonal axis? We’ve gained nothing really. Maybe there’s yet a better idea.&lt;/p&gt;  &lt;p&gt;Time to step back a little. Remember the original promise of the interface? You implement me and I give you something with “queryable” characteristics in return. However, for ages the typical way of delivering on such a promise was symmetric to the implementation. It was really all about: “I know – but only abstractly – how to use &lt;em&gt;something&lt;/em&gt; but only if you concretize that something for me.”. Hence interfaces for say serialization have predictable members like Serialize and Deserialize. And yes, the interface delivers on its promise of marking something that can do serialization as such but in a rather lame and predictable way. So what if we could deliver on the “queryable” promise without putting the burden of implementing all query operators directly on the implementor? This is where interfaces can also be “asymmetric” concerning their promise versus their implementation cost. (If I were in a really philosophical mood, I could start derailing the conversation introducing parallels with concave, convex and regular mirrors. Let’s not do this.) But how…?&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;An asymmetric interface (IImplement side)&lt;/h1&gt;  &lt;p&gt;In order to have useful query capabilities we really need two things:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Write a query &lt;/li&gt;    &lt;li&gt;Enumerate over the results &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;From the latter promise we can already infer that IQueryable&amp;lt;T&amp;gt; ought to implement IEnumerable&amp;lt;T&amp;gt;, which makes our outstanding balance for the “implementor frustration threshold” (IFT for acronym lovers) two: a generic and non-generic equivalent of GetEnumerator:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;interface&lt;/font&gt; &lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; : &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt;       &lt;br /&gt;{       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;For the former promise we already came to the conclusion that it would be unreasonable to require 47 methods or so to be implemented (btw, that would also mean that in subsequent releases of LINQ, new query operators would have to go in an IQueryable2&amp;lt;T&amp;gt; interface since interfaces do not scale well on the versioning axis – remember COM?). So what if we could do all the heavy lifting for you, just giving you one piece of information that represents an entire query. That’s what &lt;strong&gt;expression trees&lt;/strong&gt; are capable of doing. Now we end up with one more member to IQueryable&amp;lt;T&amp;gt;:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;interface&lt;/font&gt; &lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; : &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression &lt;/font&gt;Expression { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Conceptually, we could stop here. You have an expression tree that can represent an entire query (but how does it get there?) and you have a method that demands (where lazy becomes eager) you to start iterating over the results. The two query capability requirements have been fulfilled. Oh, and it’s quite predictable how the GetEnumerator would work, right? Take the expression tree, translate it into a Domain Specific Query Language (DSQL if you will), optionally cache it, send it to whatever data store you’re about to query, fetch the results, new up objects and &lt;em&gt;yield&lt;/em&gt; them back.&lt;/p&gt;  &lt;p&gt;I already raised the question about where the expression tree property’s value comes from. The answer is we need a bit of collaboration from you, the implementor, through a property called QueryProvider:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#0000ff"&gt;interface&lt;/font&gt; &lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; : &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression &lt;/font&gt;Expression { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;IQueryProvider &lt;/font&gt;QueryProvider { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }     &lt;br /&gt;}&lt;/blockquote&gt;  &lt;p&gt;An IQueryProvider is an object that knows how to create IQueryable objects, much like a factory. However, at certain points in time we’ll want you to do a different thing: instead of creating a new IQueryable, we might want you to execute a query on request (for example when you’re applying the First() query operator, eager evaluation results and we’ll need a way to kindly ask you for the value returned by the query):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;interface&lt;/font&gt; &lt;font color="#008080"&gt;IQueryProvider&lt;/font&gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; CreateQuery&amp;lt;T&amp;gt;(&lt;font color="#008080"&gt;Expression &lt;/font&gt;ex);       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; T Execute&amp;lt;T&amp;gt;(&lt;font color="#008080"&gt;Expression &lt;/font&gt;ex);       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;How lame you might think: it’s just asking me to create the IQueryable&amp;lt;T&amp;gt; on LINQ’s behalf. Yes, but you can carry out whatever tricks you need (such as propagating some connection information needed to connect to a database) inside the CreateQuery implementation. Oh, and both methods above have non-generic counterparts.&lt;/p&gt;  &lt;p&gt;In addition to the two properties and two methods above, there’s one last property I should mention for completeness: ElementType. The idea of this property is to expose the type of the entities being queried. Why do we need this? Is IQueryable&amp;lt;T&amp;gt; not telling enough, namely T? Indeed, there’s even such a remark in the MSDN documentation:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The ElementType property represents the &amp;quot;T&amp;quot; in IQueryable&amp;lt;T&amp;gt; or IQueryable(Of T).&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The reason we still have ElementType is for non-generic cases. For example, you might want to target a data store that doesn’t have an extensible schema, so you don’t need a generic parameter ‘T’. Instead, the type of the data returned by the provider is baked in, and ElementType is the way to retrieve that underlying type.&lt;/p&gt;  &lt;p&gt;Finally, we end up with the following definition of IQueryable&amp;lt;T&amp;gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;interface&lt;/font&gt; &lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; : &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression &lt;/font&gt;Expression { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;IQueryProvider &lt;/font&gt;QueryProvider { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Type &lt;/font&gt;ElementType { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;All of this might still look fancy, so let’s turn to the consumer side to clarify things. That’s were the asymmetry becomes really apparent.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;An asymmetric interface (IConsume side)&lt;/h1&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Let’s assume for a minute we have some Table&amp;lt;T&amp;gt; class that implements IQueryable&amp;lt;T&amp;gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;products = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Table&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt;();&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Given our derived interface definition for IQueryable&amp;lt;T&amp;gt; we don’t really get much “query capabilities”, do we? Right, we can ask this instance for things like ElementType (which really will be typeof(T)) and fairly abstract notions of Expression and QueryProvider. But no way we have query operators such a Where and Select available already. However, as you’ll know by know, LINQ relies on such operators. Indeed, take a look at the following query:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;products = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Table&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt;();       &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;products &lt;font color="#0000ff"&gt;where &lt;/font&gt;p.Price &amp;gt; 100 &lt;font color="#0000ff"&gt;select &lt;/font&gt;p.Name;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The way this gets translated by the compiler looks as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Table&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt; products = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Table&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt;();       &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = products.Where(p =&amp;gt; p.Price &amp;gt; 100).Select(p =&amp;gt; p.Name);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;but where’s the Where? The answer lies in extension methods of course. Once we have System.Linq in scope, a (static) class called Queryable is in reach which exposes extension methods for IQueryable&amp;lt;T&amp;gt;. This is precisely why IQueryable&amp;lt;T&amp;gt; deserves the title of “funny interface” since it’s most likely the first interface that has been designed with a split view in mind. On the one hand, there’s the real “interface interface”, i.e. in CLR terms. But on top of that, extension methods provide the really useful interface functionality and act virtually as default method implementations in interfaces. That is, you don’t need to implement a whole bunch of query operator methods to get their functionality.&lt;/p&gt;  &lt;p&gt;So, how do those methods work? Before going there, what about refreshing our mind on the LINQ to Objects implementation of those operators, as defined in System.Linq.Enumerable as extension methods on IEnumerable&amp;lt;T&amp;gt;. Just to pick one, consider Where:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#0000ff"&gt;bool&lt;/font&gt;&amp;gt; predicate)       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(T item &lt;font color="#0000ff"&gt;in&lt;/font&gt; source)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(predicate(item))       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;item;       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;u&gt;Note:&lt;/u&gt; I’ve omitted the (a little tricky to implement – why?) exception throwing code in case source or predicate are null; this is left as an exercise for the reader. Solutions can be found in &lt;a href="http://www.codeplex.com/LINQSQO"&gt;www.codeplex.com/LINQSQO&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Besides client-side execution using iterators, there are a few important things to notice. First, here we’re extending on IEnumerable&amp;lt;T&amp;gt;. Although IQueryable&amp;lt;T&amp;gt; implements IEnumerable&amp;lt;T&amp;gt;, LINQ to Objects operators won’t be used when applying query operators on an IQueryable&amp;lt;T&amp;gt; data source because the latter type is more specific. If one wants to switch to LINQ to Objects semantics, AsEnumerable&amp;lt;T&amp;gt;() can be called. The second important thing is the type of the second parameter (on the call side this will look like the first and only parameter because we’re looking at an extension method). It’s just a Func&amp;lt;T, bool&amp;gt;, which is a delegate. This triggers the compiler to create an anonymous method:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;&lt;u&gt;IEnumerable&lt;/u&gt;&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt; products = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;List&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt;();     &lt;br /&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt; res = products.Where(&lt;font color="#0000ff"&gt;delegate &lt;/font&gt;(&lt;font color="#008080"&gt;Product &lt;/font&gt;p) { &lt;font color="#0000ff"&gt;return &lt;/font&gt;p.Price &amp;gt; 100; }).Select(&lt;font color="#0000ff"&gt;delegate &lt;/font&gt;(&lt;font color="#008080"&gt;Product &lt;/font&gt;p) { &lt;font color="#0000ff"&gt;return &lt;/font&gt;p.Name; });&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Now, switch to the IQueryable&amp;lt;T&amp;gt; counterpart defined in System.Linq.Queryable, ignoring the implementation for a second:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#0000ff"&gt;static &lt;/font&gt;&lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IQueryable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#0000ff"&gt;bool&lt;/font&gt;&amp;gt;&amp;gt; predicate)&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Obviously the return type and first parameter type are different, but more importantly is the different type for the predicate parameter. This time it’s an &lt;strong&gt;Expression&lt;/strong&gt;&amp;lt;…&amp;gt; of that same delegate Func&amp;lt;T, bool&amp;gt; type. When the compiler tries to assign a lambda expression to such an Expression&amp;lt;T&amp;gt; it emits code to create an expression tree, representing the lambda’s semantics, at runtime:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;&lt;u&gt;IQueryable&lt;/u&gt;&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt; products = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Table&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt;();     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;p = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#008080"&gt;Product&lt;/font&gt;), &lt;font color="#800000"&gt;“p”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;LambdaExpression &lt;/font&gt;&amp;lt;&amp;gt;__predicate = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda(&lt;font color="#008080"&gt;Expression&lt;/font&gt;.Greater(&lt;font color="#008080"&gt;Expression&lt;/font&gt;.Property(p, &lt;font color="#800000"&gt;“Price”&lt;/font&gt;), &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Constant(100)), p);     &lt;br /&gt;&lt;font color="#008080"&gt;LambdaExpression &lt;/font&gt;&amp;lt;&amp;gt;__projection = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda(&lt;font color="#008080"&gt;Expression&lt;/font&gt;.Property(p, &lt;font color="#800000"&gt;“Name”&lt;/font&gt;), p);     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = products.Where(&amp;lt;&amp;gt;__predicate).Select(&amp;lt;&amp;gt;__projection);&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;So, we can already see how a LINQ query ends up as a chain of query operator method calls that are all implemented as extension methods on IQueryable&amp;lt;T&amp;gt; and take in their “function parameter” as an expression tree, so that interpretation and translation can be deferred till runtime. Indeed, an expression tree representing p =&amp;gt; p.Price &amp;gt; 100 can easily be translated into a WHERE clause in SQL or whatever equivalent in another DSQL.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The inner workings of the beast&lt;/h1&gt;  &lt;p&gt;Remaining question is how System.Linq.Queryable.* methods are implemented. Obviously no iterators, there’s nothing that can be done client-side. Instead we want to end up with a giant expression tree representing a query, originating from a chain of query operator method calls:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;products.Where(&amp;lt;&amp;gt;__predicate).Select(&amp;lt;&amp;gt;__projection)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The query above contains no less than 5 ingredients:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The query source, i.e. “products”, containing all the relevant information to connect to the data store. &lt;/li&gt;    &lt;li&gt;First we want to filter the data using a “Where” clause which      &lt;ol&gt;       &lt;li&gt;takes in a predicate as an expression tree &lt;/li&gt;     &lt;/ol&gt;   &lt;/li&gt;    &lt;li&gt;Next we want to project the results of the previous operator using      &lt;ol&gt;       &lt;li&gt;a projection represented as an expression tree &lt;/li&gt;     &lt;/ol&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;After executing the line of code above, we get an IQueryable&amp;lt;string&amp;gt; in return (a string because the projection maps the Product objects onto strings using p.Name), one that should contain all of the information outlined above. Breaking this down, products is an IQueryable&amp;lt;Product&amp;gt; and hence it has an Expression property representing point ‘1’ above – data about the query source. When applying Where to this, we take all existing query information (from the “left hand side of the .”) through the Expression property and add the knowledge we’re about to apply Where with a given predicate (point ‘2’ above), resulting in a new IQueryable&amp;lt;Product&amp;gt;. Finally, Select is applied, again taking the original information via the Expression property, extending it with “Select &lt;em&gt;some projection”&lt;/em&gt;, resulting in a new IQueryable&amp;lt;string&amp;gt; in this case. To wrap up this sample, the code above creates no less than three distinct IQueryable&amp;lt;T&amp;gt; instances (that is, including “products” in this count).&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;A picture is worth a thousand words:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheMostFunnyInterfaceOfTheYearIQueryable_7DEB/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="404" alt="image" src="http://bartdesmet.info/images_wlw/TheMostFunnyInterfaceOfTheYearIQueryable_7DEB/image_thumb.png" width="644" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Inside the implementation of Where&amp;lt;T&amp;gt;, we:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;ask the original source for the expression tree that represents all the information about the query gathered so far (really the left of the ‘.’ when calling Where&amp;lt;T&amp;gt; through extension method syntax); &lt;/li&gt;    &lt;li&gt;combine this with the passed in predicate expression tree; &lt;/li&gt;    &lt;li&gt;grab the MethodInfo for the currently executing method, i.e. Queryable.Where, which will act as the representation for the query operator in the resulting expression tree; &lt;/li&gt;    &lt;li&gt;combine all of the above in a MethodCallExpression; &lt;/li&gt;    &lt;li&gt;feed the resulting MethodCallExpression into the IQueryProvider’s CreateQuery&amp;lt;T&amp;gt; method to end up with a new IQueryable&amp;lt;T&amp;gt;. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Subsequent query operator calls, e.g. to Select&amp;lt;T,R&amp;gt;, will continue this process of taking the original query expression and building a new one out of it by extending it with information about the query operator and its arguments (e.g. the projection lambda expression).&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;Quite often, the recommendation for using extension methods is to use them only to “extend” (sealed) classes with helper methods, if you don’t have a way to extend those yourself. In other words, if you’re the owner of a class, you should consider extending the class’s functionality rather than using extension methods are your primary extension mechanism. This recommendation is absolutely correct. However, when dealing with (what I refer to as) “asymmetric” interfaces, extension methods offer an interesting – albeit advanced – capability to separate the bare minimum extensibility points (the real “CLR interface”) from the offered functionality (brought in scope – or “woven in” – through extension methods via a namespace import) to reduce the tension between interface creator and implementor. In this post, you’ve seen one of the pioneers employing this technique: IQueryable&amp;lt;T&amp;gt;. Before you even consider following this technique, think about all the options you have: pure interfaces (keeping the “implementor frustration threshold” in mind), abstract base classes (keeping the single inheritance restriction in mind) and extension method based interface asymmetry.&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13863" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category></item></channel></rss>