<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">

<channel>
	<title>Solutionizing .NET</title>
	
	<link>http://solutionizing.net</link>
	<description>Random thoughts on custom development in SharePoint.</description>
	<lastBuildDate>Sat, 17 Oct 2009 07:29:28 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain="solutionizing.net" port="80" path="/?rsscloud=notify" registerProcedure="" protocol="http-post" />
<image>
		<url>http://www.gravatar.com/blavatar/db5c1b460681b4face5c439ce357375c?s=96&amp;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Solutionizing .NET</title>
		<link>http://solutionizing.net</link>
	</image>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/SolutionizingDotNet" type="application/rss+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Is Functional Abstraction Too Clever?</title>
		<link>http://solutionizing.net/2009/10/17/is-functional-abstraction-too-clever/</link>
		<comments>http://solutionizing.net/2009/10/17/is-functional-abstraction-too-clever/#comments</comments>
		<pubDate>Sat, 17 Oct 2009 07:29:28 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=710</guid>
		<description><![CDATA[I received a rather interesting comment on a recent Stack Overflow answer:
This code seems too clever by half. Is it art? – PeterAllenWebb
The code in question was a functional solution to an algorithm described approximately as follows:
Draw n−1 numbers at random, in the range 1 to m−1. Add 0 and m to the list and order [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=710&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I received a rather interesting comment on a recent Stack Overflow answer:</p>
<blockquote><p>This code seems too clever by half. Is it art? – <a href="http://stackoverflow.com/users/21365/peterallenwebb">PeterAllenWebb</a></p></blockquote>
<p>The <a title="Split value in 24 randomly sized parts using C#" href="http://stackoverflow.com/questions/1581394/split-value-in-24-randomly-sized-parts-using-c/1581464#1581464">code in question</a> was a functional solution to an algorithm described approximately as follows:</p>
<blockquote><p>Draw <em>n</em>−1 numbers at random, in the range 1 to <em>m</em>−1. Add 0 and <em>m</em> to the list and order these numbers. The difference between each two consecutive numbers gives you a return value.</p></blockquote>
<p>Which I solved like this, with <em>n</em> = <code>slots</code> and <em>m</em> = <code>max</code>:</p>
<pre>static int[] GetSlots(int slots, int max)
{
    return new Random().Values(1, max)
                       .Take(slots - 1)
                       .Append(0, max)
                       .OrderBy(i =&gt; i)
                       .Pairwise((x, y) =&gt; y - x)
                       .ToArray();
}</pre>
<p>Using a few extension methods:</p>
<ul>
<li><code>Values()</code> returns an infinite sequence of random values within the specified range.</li>
<li><code>Append()</code> takes a <code>params</code> array and appends its arguments to the original sequence.</li>
<li><code>Pairwise()</code> generates a sequence from calculations on pairs of consecutive elements in the original sequence.</li>
</ul>
<p>I can see how one would think the code is clever; however, I&#8217;m not sure what would qualify it as <em>too</em> clever. Every method call has a well-defined purpose and maps directly to part of the original algorithm:</p>
<ol>
<li>From random numbers in the range 1 to <em>m</em>−1&#8230;</li>
<li>&#8230;draw <em>n</em>−1.</li>
<li>Add 0 and <em>m</em> to the list&#8230;</li>
<li>&#8230;and order these numbers.</li>
<li>The difference between each two consecutive numbers&#8230;</li>
<li>&#8230;gives you a return value [in the array].</li>
</ol>
<p>As far as I&#8217;m concerned, a solution couldn&#8217;t get much clearer than this, but that&#8217;s easy enough for me to say—what do you think? Is there a better way to express the algorithm? Would an imperative solution with shared state be more readable? How about maintainable?</p>
<p>For example, one could add the requirement that the random numbers not be repeated so that the difference between adjacent numbers is always nonzero. Updating the functional solution is as simple as adding a Distinct() call:</p>
<pre>    return new Random().Values(1, max)
<strong>                       .Distinct()</strong>
                       .Take(slots - 1)
                       ...</pre>
<p>To me, this is the value proposition of functional programming. By expressing the algorithm in terms of common operations, we&#8217;re able to spend more time thinking about the problem than the details of the solution. A similar change in an imperative implementation would almost certainly have been more involved and prone to error.</p>
<p>For completeness, here are the implementations of the extension methods used:</p>
<pre>public static IEnumerable&lt;int&gt; Values(this Random random, int minValue, int maxValue)
{
    while (true)
        yield return random.Next(minValue, maxValue);
}

public static IEnumerable&lt;TResult&gt; Pairwise&lt;TSource, TResult&gt;(
    this IEnumerable&lt;TSource&gt; source,
    Func&lt;TSource, TSource, TResult&gt; resultSelector)
{
    TSource previous = default(TSource);

    using (var it = source.GetEnumerator())
    {
        if (it.MoveNext())
            previous = it.Current;

        while (it.MoveNext())
            yield return resultSelector(previous, previous = it.Current);
    }
}

public static IEnumerable&lt;T&gt; Append&lt;T&gt;(this IEnumerable&lt;T&gt; source, params T[] args)
{
    return source.Concat(args);
}</pre>
<p>This also reminds me that <a title="Jimmy Bogard" href="http://www.lostechies.com/blogs/jimmy_bogard/default.aspx">Jimmy</a> posted a similar <code>Append()</code> method as part of his latest post on <a title="More missing LINQ operators" href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/10/15/more-missing-linq-operators.aspx">missing LINQ operators</a>. I used to use a version similar to his, but have found the <code>params</code> version to be more flexible (and easier to implement). Its <code>Prepend()</code> counterpart is similarly trivial:</p>
<pre>public static IEnumerable&lt;T&gt; Prepend&lt;T&gt;(this IEnumerable&lt;T&gt; source, params T[] args)
{
    return args.Concat(source);
}</pre>
 Tagged: Functional Programming <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/710/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/710/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/710/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/710/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/710/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/710/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/710/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/710/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/710/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/710/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=710&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/InLUCAubVs4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/10/17/is-functional-abstraction-too-clever/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Refactoring with Iterators: Prime Factors</title>
		<link>http://solutionizing.net/2009/09/30/refactoring-with-iterators-prime-factors/</link>
		<comments>http://solutionizing.net/2009/09/30/refactoring-with-iterators-prime-factors/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 15:16:37 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Iterators]]></category>
		<category><![CDATA[Refactor]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=694</guid>
		<description><![CDATA[Andrew Woodward recently posted a comparison of his test-driven Prime Factors solution to one written by Uncle Bob. In the comments, someone suggested that Andrew use an iterator instead so I thought I&#8217;d give it a try.
First, let&#8217;s repost the original code:
private const int SMALLEST_PRIME = 2;

public List&#60;int&#62; Generate(int i)
{
    List&#60;int&#62; primes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=694&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://www.21apps.com/">Andrew Woodward</a> recently posted a <a title="Comparing myself to Uncle Bob Martin" href="http://www.21apps.com/development/comparing-myself-to-uncle-bob-martin/">comparison of his test-driven Prime Factors solution</a> to <a title="Prime Factors Kata" href="http://www.butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata">one written by</a> <a title="Robert C. Martin" href="http://butunclebob.com/">Uncle Bob</a>. In the comments, someone suggested that Andrew use an iterator instead so I thought I&#8217;d give it a try.</p>
<p>First, let&#8217;s repost the original code:</p>
<pre>private const int SMALLEST_PRIME = 2;

public List&lt;int&gt; Generate(int i)
{
    List&lt;int&gt; primes = new List&lt;int&gt;();
    int divider = SMALLEST_PRIME;
    while (HasPrimes(i))
    {
        while (IsDivisable(i, divider))
        {
            i = AddPrimeToProductsAndReduce(i, primes, divider);
        }
        divider++;
    }
    return primes;
}

private bool IsDivisable(int i, int divider)
{
    return i%divider == 0;
}

private bool HasPrimes(int i)
{
    return i &gt;= SMALLEST_PRIME;
}

private int AddPrimeToProductsAndReduce(int i, List&lt;int&gt; primes, int prime)
{
    primes.Add(prime);
    i /= prime;
    return i;
}</pre>
<p>By switching our method to return <code>IEnumerable&lt;int&gt;</code>, we can replace the <code>primes</code> list with an iterator. We will also remove the AddPrimeToProducts functionality from that helper method since we don&#8217;t have the list any more:</p>
<pre>public IEnumerable&lt;int&gt; Generate(int i)
{
    int divider = SMALLEST_PRIME;
    while (HasPrimes(i))
    {
        while (IsDivisable(i, divider))
        {
            yield return divider;
            i = Reduce(i, divider);
        }
        divider++;
    }
}

private int Reduce(int i, int prime)
{
    return i / prime;
}</pre>
<p>I think this is a good change for three reasons:</p>
<ol>
<li>There&#8217;s nothing about the problem that requires a <code>List&lt;int&gt;</code> be returned, we just want a sequence of the factors.</li>
<li><code>AddPrimeToProductsAndReduce</code> suggested that it had a side effect, but exactly what wasn&#8217;t immediately obvious.</li>
<li>It&#8217;s much easier to see what values are being included in the result.</li>
</ol>
<p>That said, I think we can clean this up even more with a second iterator. Specifically, I think we should break out the logic for our candidate factors:</p>
<pre>private IEnumerable&lt;int&gt; Divisors
{
    get
    {
        int x = SMALLEST_PRIME;
        while (true)
            yield return x++;
    }
}</pre>
<p>Which allows us to separate the logic for generating a divider from the code that consumes it:</p>
<pre>public IEnumerable&lt;int&gt; Generate(int toFactor)
{
    foreach (var divider in Divisors)
    {
        if (!HasPrimes(toFactor))
            break;

        while (IsDivisable(toFactor, divider))
        {
            yield return divider;
            toFactor = Reduce(toFactor, divider);
        }
    }
}</pre>
<p>We should also eliminate the negation by flipping <code>HasPrimes</code> to become <code>IsFactored</code>:</p>
<pre>public IEnumerable&lt;int&gt; Generate(int toFactor)
{
    foreach (var divider in Divisors)
    {
        if (IsFactored(toFactor))
            break;

        while (IsDivisable(toFactor, divider))
        {
            yield return divider;
            toFactor = Reduce(toFactor, divider);
        }
    }
}

private bool IsFactored(int i)
{
    return i &lt;= 1;
}</pre>
<p>This does introduce a (very) minor inefficiency in that the <code>Divisors</code> enumerator will <code>MoveNext()</code> one extra time before breaking out of the loop, which could be mitigated by checking <code>IsFactored</code> both before the <code>foreach</code> and after the <code>while</code> loop. Less readable, insignificantly more efficient&#8230;take your pick.</p>
<p>The other advantage to breaking out the logic to generate <code>Divisors</code> is that we can easily pick smarter candidates. One option is to skip even numbers greater than 2. An even better optimization takes advantage of the fact that all primes greater than 3 are of the form x±1 where x is a multiple of 6:</p>
<pre>private IEnumerable&lt;int&gt; Divisors
{
    get
    {
        yield return 2;
        yield return 3;
        int i = 6;
        while (true)
        {
            yield return i - 1;
            yield return i + 1;
            i += 6;
        }
    }
}</pre>
<p>Implementing this sort of logic in the original version would have been much more difficult, both in terms of correctness and readability.</p>
 Tagged: Iterators, Refactor <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/694/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=694&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/muf101XHgO8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/09/30/refactoring-with-iterators-prime-factors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Hacking LINQ Expressions: Join With Comparer</title>
		<link>http://solutionizing.net/2009/09/19/hacking-linq-expressions-join-with-comparer/</link>
		<comments>http://solutionizing.net/2009/09/19/hacking-linq-expressions-join-with-comparer/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 18:13:27 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Hacking LINQ]]></category>
		<category><![CDATA[IEqualityComparer]]></category>
		<category><![CDATA[LINQ Join]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=681</guid>
		<description><![CDATA[In this installment of my Hacking LINQ series we&#8217;ll take a look at providing an IEqualityComparer for use in a LINQ join clause.
The Problem
Many of the Standard Query Operators require comparing sequence elements and the default query providers are kind enough to give us overloads that accept a suitable comparer. Among these operators, Join and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=681&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this installment of my <a href="http://solutionizing.net/tag/hacking-linq/">Hacking LINQ</a> series we&#8217;ll take a look at providing an <code>IEqualityComparer</code> for use in a LINQ <code>join</code> clause.</p>
<h2>The Problem</h2>
<p>Many of the <a title="Standard Query Operators Overview" href="http://msdn.microsoft.com/en-us/library/bb397896.aspx">Standard Query Operators</a> require comparing sequence elements and the default query providers are kind enough to give us overloads that accept a suitable comparer. Among these operators, <code>Join</code> and <code>GroupJoin</code> have perhaps the most useful query syntax:</p>
<pre> var res = from s in States
          join a in AreaCodes
            on s.Abbr equals a.StateAbbr
          select new { s.Name, a.AreaCode };</pre>
<p>While a bit more verbose, I find the intent much easier to read then the method equivalent:</p>
<pre>var res = States.Join(AreaCodes,
                      s =&gt; s.Abbr, a =&gt; a.StateAbbr,
                      (s, a) =&gt; new { s.Name, a.AreaCode });</pre>
<p>Or maybe I&#8217;ve just spent too much time in SQL. Either way, I thought it would be useful to support joins by a comparer.</p>
<h2>The Goal</h2>
<p>We will use another extension method to specify how the join should be performed:</p>
<pre>var res = from s in States
          join a in AreaCodes.WithComparer(StringComparer.OrdinalIgnoreCase)
            on s.Abbr equals a.StateAbbr
          select new { s.Name, a.AreaCode };</pre>
<p>We can also support the same syntax for group joins:</p>
<pre>var res = from s in States
          join a in AreaCodes.WithComparer(StringComparer.OrdinalIgnoreCase)
            on s.Abbr equals a.StateAbbr into j
          select new { s.Name, Count = j.Count() };</pre>
<h2>The Hack</h2>
<p>As with most LINQ hacks, we&#8217;re going to use the result of <code>WithComparer</code> to call a specialized version of <code>Join</code> or <code>GroupJoin</code>, in this case by providing a replacement for the join&#8217;s inner sequence:</p>
<pre>var res = States.Join(AreaCodes.WithComparer(StringComparer.OrdinalIgnoreCase),
                      s =&gt; s.Abbr, a =&gt; a.StateAbbr,
                      (s, a) =&gt; new { s.Name, a.AreaCode });</pre>
<p>Eventually leading to this method call:</p>
<pre>var res = States.Join(AreaCodes,
                      s =&gt; s.Abbr, a =&gt; a.StateAbbr,
                      (s, a) =&gt; new { s.Name, a.AreaCode },
                      StringComparer.OrdinalIgnoreCase);</pre>
<p>Since we need both the inner collection we&#8217;re extending and the comparer, we can guess our extension method will be implemented something like this:</p>
<pre>public static JoinComparerProvider&lt;T, TKey&gt; WithComparer&lt;T, TKey&gt;(
    this IEnumerable&lt;T&gt; inner, IEqualityComparer&lt;TKey&gt; comparer)
{
    return new JoinComparerProvider&lt;T, TKey&gt;(inner, comparer);
}</pre>
<p>With a trivial provider implementation:</p>
<pre>public sealed class JoinComparerProvider&lt;T, TKey&gt;
{
    internal JoinComparerProvider(IEnumerable&lt;T&gt; inner, IEqualityComparer&lt;TKey&gt; comparer)
    {
        Inner = inner;
        Comparer = comparer;
    }

    public IEqualityComparer&lt;TKey&gt; Comparer { get; private set; }
    public IEnumerable&lt;T&gt; Inner { get; private set; }
}</pre>
<p>The final piece is our <code>Join</code> overload:</p>
<pre>public static IEnumerable&lt;TResult&gt; Join&lt;TOuter, TInner, TKey, TResult&gt;(
    this IEnumerable&lt;TOuter&gt; outer,
    JoinComparerProvider&lt;TInner, TKey&gt; inner,
    Func&lt;TOuter, TKey&gt; outerKeySelector,
    Func&lt;TInner, TKey&gt; innerKeySelector,
    Func&lt;TOuter, TInner, TResult&gt; resultSelector)
{
    return outer.Join(inner.Inner, outerKeySelector, innerKeySelector,
                      resultSelector, inner.Comparer);
}</pre>
<p>Implementations of <code>GroupJoin</code> and their <code>IQueryable</code> counterparts are similarly trivial.</p>
 Tagged: Hacking LINQ, IEqualityComparer, LINQ Join <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/681/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=681&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/uMh5gnUzzj8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/09/19/hacking-linq-expressions-join-with-comparer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Hacking LINQ Expressions: Select With Index</title>
		<link>http://solutionizing.net/2009/09/15/hacking-linq-expressions-select-with-index/</link>
		<comments>http://solutionizing.net/2009/09/15/hacking-linq-expressions-select-with-index/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 09:04:12 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Hacking LINQ]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=671</guid>
		<description><![CDATA[First, a point of clarification: I use LINQ Expressions to mean (Language-INtegrated) Query Expressions (the language feature) rather than Expression Trees (the .NET 3.5 library in System.Linq.Expressions).
So what do I mean by &#8220;Hacking LINQ Expressions&#8221;? Quite simply, I&#8217;m not content with the rather limited set of operations that query expressions allow me to represent. By [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=671&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>First, a point of clarification: I use LINQ Expressions to mean (Language-INtegrated) Query Expressions (the language feature) rather than Expression Trees (the .NET 3.5 library in System.Linq.Expressions).</p>
<p>So what do I mean by &#8220;Hacking LINQ Expressions&#8221;? Quite simply, I&#8217;m not content with the rather limited set of operations that query expressions allow me to represent. By understanding how queries are translated, we can use various techniques to broaden our expressive reach. I have already documented one such hack for <a title="Using IDisposables with LINQ" href="http://solutionizing.net/2009/07/23/using-idisposables-with-linq/">managing IDisposable objects with LINQ</a>, so I guess we can call this the second in an unbounded series.</p>
<h2>The Problem</h2>
<p>In thinking over use cases for <a title="Functional Construction for ASP.NET Web Forms" href="http://solutionizing.net/2009/09/13/functional-construction-for-asp-net-web-forms/">functional construction of web control trees</a>, I paused to think through how I would express alternate row styling. My mind immediately jumped to the <a title="Enumerable.Select&lt;TSource, TResult&gt; Method (IEnumerable&lt;TSource&gt;, Func&lt;TSource, Int32, TResult&gt;)" href="http://msdn.microsoft.com/en-us/library/bb534869.aspx">overload of Select()</a> that exposes the current element&#8217;s index:</p>
<pre>Controls.Add(
    new Table().WithControls(
        data.Select((x, i) =&gt;
            new TableRow() {
                CssClass = i % 2 == 0 ? "" : "alt"
            }.WithControls(
                new TableCell().WithControls(x)
            )
        )
    )
);</pre>
<p>This works fine for simple cases, but breaks down for more complex queries:</p>
<pre>Controls.Add(
    new Table().WithControls((
        from x in Xs
        join y in Ys on x.Key equals y.Key
        select new { x, y }
        ).Select((z, i) =&gt;
            new TableRow() {
                CssClass = i % 2 == 0 ? "" : "alt"
            }.WithControls(
                new TableCell().WithControls(z.x.ValueX, z.y.ValueY)
            )
        )
    )
);</pre>
<h2>The Goal</h2>
<p>Instead, I propose a simple extension method to retrieve an index at arbitrary points in a query:</p>
<pre>var res = from x in data
          from i in x.GetIndex()
          select new { x, i };</pre>
<p>Or our control examples:</p>
<pre>Controls.Add(
    new Table().WithControls(
        from x in data
        from i in x.GetIndex()
        select new TableRow() {
            CssClass = i % 2 == 0 ? "" : "alt"
        }.WithControls(
            new TableCell().WithControls(x)
        )
    )
);

Controls.Add(
    new Table().WithControls(
        from x in Xs
        join y in Ys on x.Key equals y.Key
        from i in y.GetIndex()
        select new TableRow() {
            CssClass = i % 2 == 0 ? "" : "alt"
        }.WithControls(
            new TableCell().WithControls(x.ValueX, y.ValueY)
        )
    )
);</pre>
<p>Much like in the <code>IDisposable</code> solution, we use a <code>from</code> clause to act as an intermediate assignment. But in this case our hack is a bit trickier than a simple iterator.</p>
<h2>The Hack</h2>
<p>For this solution we&#8217;re going to take advantage of how multiple <code>from</code> clauses are translated:</p>
<pre>var res = data.SelectMany(x =&gt; x.GetIndex(), (x, i) =&gt; new { x, i });</pre>
<p>Looking at the parameter list, we see that our <code>collectionSelector</code> should return the result of <code>x.GetIndex()</code> and our <code>resultSelector</code>&#8217;s second argument needs to be an <code>int</code>:</p>
<pre>public static IEnumerable&lt;TResult&gt; SelectMany&lt;TSource, TResult&gt;(
    this IEnumerable&lt;TSource&gt; source,
    Func&lt;TSource, SelectIndexProvider&gt; collectionSelector,
    Func&lt;TSource, int, TResult&gt; resultSelector)</pre>
<p>The astute observer will notice that the signature of this <code>resultSelector</code> exactly matches the <code>selector</code> used by <code>Select</code>&#8217;s with-index overload, trivializing the method implementation:</p>
<pre>{
    return source.Select(resultSelector);
}</pre>
<p>Note that we&#8217;re not even using <code>collectionSelector</code>! We&#8217;re just using its return type as a flag to force the compiler to use this version of <code>SelectMany()</code>. The rest of the pieces are incredibly simple now that we know the actual <code>SelectIndexProvider</code> value is never used:</p>
<pre>public sealed class SelectIndexProvider
{
    private SelectIndexProvider() { }
}

public static SelectIndexProvider GetIndex&lt;T&gt;(this T element)
{
    return null;
}</pre>
<p>And for good measure, an equivalent version to extend IQueryable&lt;&gt;:</p>
<pre>public static IQueryable&lt;TResult&gt; SelectMany&lt;TSource, TResult&gt;(
    this IQueryable&lt;TSource&gt; source,
    Expression&lt;Func&lt;TSource, SelectIndexProvider&gt;&gt; collectionSelector,
    Expression&lt;Func&lt;TSource, int, TResult&gt;&gt; resultSelector)
{
    return source.Select(resultSelector);
}</pre>
<p>Because we&#8217;re just calling <code>Select()</code>, the query expression isn&#8217;t even aware of the call to <code>GetIndex()</code>:</p>
<blockquote><p>System.Linq.Enumerable+&lt;RangeIterator&gt;d__b1.Select((x, i) =&gt; (x * i))</p></blockquote>
<p>We&#8217;re essentially providing our own syntactic sugar over the sugar already provided by query expressions. Pretty sweet, eh?</p>
<p>As a final exercise for the reader, what would this print?</p>
<pre>var res = from x in Enumerable.Range(1, 5)
          from i in x.GetIndex()
          from y in Enumerable.Repeat(i, x)
          where y % 2 == 1
          from j in 0.GetIndex()
          select i+j;

foreach (var r in res)
    Console.WriteLine(r);</pre>
 Tagged: Hacking LINQ <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/671/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/671/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/671/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/671/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/671/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/671/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/671/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/671/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/671/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/671/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=671&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/bvxROtbfHF8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/09/15/hacking-linq-expressions-select-with-index/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Construction for ASP.NET Web Forms</title>
		<link>http://solutionizing.net/2009/09/13/functional-construction-for-asp-net-web-forms/</link>
		<comments>http://solutionizing.net/2009/09/13/functional-construction-for-asp-net-web-forms/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 08:58:44 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[WebParts & Controls]]></category>
		<category><![CDATA[Functional Construction]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=647</guid>
		<description><![CDATA[System.Xml.Linq (a.k.a. LINQ to XML) introduces a nifty approach to creating XML elements called functional construction. I&#8217;m not entirely sure why they call it functional given that constructing an object graph is a decidedly non-functional task in the traditional sense of the word, but I digress.
Functional construction has three key features:

Constructors accept arguments of various [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=647&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>System.Xml.Linq (a.k.a. LINQ to XML) introduces a nifty approach to creating XML elements called <a title="Functional Construction (LINQ to XML)" href="http://msdn.microsoft.com/en-us/library/bb387019.aspx">functional construction</a>. I&#8217;m not entirely sure why they call it functional given that constructing an object graph is a decidedly non-functional task in the traditional sense of the word, but I digress.</p>
<p>Functional construction has three key features:</p>
<ol>
<li>Constructors accept arguments of various types, handling them appropriately.</li>
<li>Constructors accept a <code>params</code> array of type <code>Object</code> to enable creation of complex objects.</li>
<li>If an argument implements <code>IEnumerable</code>, the objects within the sequence are added.</li>
</ol>
<p>If you haven&#8217;t seen it in action, I encourage you to take a look at the examples on MSDN and elsewhere—it really is pretty slick. This post will show how a similar technique can be used to build control trees in ASP.NET web forms (and probably WinForms with minimal adjustment).</p>
<p>Basic functional construction can be implemented using two relatively simple extension methods:</p>
<pre>public static void Add(this ControlCollection @this, object content)
{
    if (content is Control)
        @this.Add((Control)content);
    else if (content is IEnumerable)
        foreach (object c in (IEnumerable)content)
            @this.Add(c);
    else if (content != null)
        @this.Add(new LiteralControl(content.ToString()));
}

public static void Add(this ControlCollection @this, params object[] args)
{
    @this.Add((IEnumerable)args);
}</pre>
<p>We handle four cases:</p>
<ol>
<li>Control? Add it.</li>
<li>Sequence? Add each.</li>
<li>Other value? Add literal.</li>
<li>Null? Ignore.</li>
</ol>
<p>And our <code>params</code> overload just calls its arguments a sequence and defers to the other.</p>
<p>In the time-honored tradition of contrived examples:</p>
<pre>Controls.Add(
    new Label() { Text = "Nums:" },
    "&amp;nbsp;",
    from i in Enumerable.Range(1, 6)
    group i by i % 2
);</pre>
<p>This would render &#8220;Nums: 135246&#8243;. Note that the result of that LINQ expression is a sequence of sequences, which is flattened automatically and converted into literals. For comparison, here&#8217;s an equivalent set of statements:</p>
<pre>Controls.Add(new Label() { Text = "Nums:" });
Controls.Add(new LiteralControl("&amp;nbsp;"));
foreach (var g in from i in Enumerable.Range(1, 6)
                  group i by i % 2)
    foreach (var i in g)
        Controls.Add(new LiteralControl(i.ToString()));</pre>
<p>Hopefully seeing them side by side makes it clear why this new method of construction might have merit. But we&#8217;re not done yet.</p>
<h2>Expressions, Expressions, Expressions</h2>
<p>Many language features introduced in C# 3.0 and Visual Basic 9 make expressions increasingly important. By expressions I mean a single &#8220;line&#8221; of code that returns a value. For example, an object initializer is a single expression&#8230;</p>
<pre>var tb = new TextBox()
{
    ID = "textBox1",
    Text = "Text"
};</pre>
<p>&#8230; that represents several statements &#8230;</p>
<pre>var tb = new TextBox()
tb.ID = "textBox1";
tb.Text = "Text";</pre>
<p>That single TextBox expression can then be used in a number of places that its statement equivalent can&#8217;t: in another object initializer, in a collection initializer, as a parameter to a method, in a .NET 3.5 expression tree, the list goes on. Unfortunately, many older APIs simply aren&#8217;t built to work in an expression-based world. In particular, initializing subcollections is a considerable pain. However, we can extend the API to handle this nicely:</p>
<pre>public static T WithControls&lt;T&gt;(this T @this, params object[] content) where T : Control
{
    if(@this != null)
        @this.Controls.Add(content);
    return @this;
}</pre>
<p>The key is the return value: Control in, Control out. We can now construct and populate a container control with a single expression. For example, we could build a dictionary list (remember those?) from our groups:</p>
<pre>Controls.Add(
    new HtmlGenericControl("dl")
    .WithControls(
        from i in Enumerable.Range(1, 6)
        group i by i % 2 into g
        select new [] {
            new HtmlGenericControl("dt")
            { InnerText = g.Key == 0 ? "Even" : "Odd" },
            new HtmlGenericControl("dd")
            .WithControls(g)
        }
    )
);</pre>
<p>Which would render this:</p>
<blockquote><dl>
<dt>Odd</dt>
<dd>135</dd>
<dt>Even</dt>
<dd>246</dd>
</dl>
</blockquote>
<p>Without the ability to add controls within an expression, this result would require nested loops with local variables to store references to the containers. The actual code produced by the compiler would be nearly identical, but I find the expressions much easier to work with. Similarly, we can easily populate tables. Let&#8217;s build a cell per number:</p>
<pre>Controls.Add(
    new Table().WithControls(
        from i in Enumerable.Range(1, 6)
        group i by i % 2 into g
        select new TableRow().WithControls(
            new TableCell()
            { Text = g.Key == 0 ? "Even" : "Odd" },
            g.Select(n =&gt; new TableCell().WithControls(n))
        )
    )
);</pre>
<p>In a future post I&#8217;ll look at some other extensions we can use to streamline the construction and initialization of control hierarchies.</p>
 Tagged: Functional Construction <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/647/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=647&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/UWyG4FpnJa8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/09/13/functional-construction-for-asp-net-web-forms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Simplifying LazyLinq</title>
		<link>http://solutionizing.net/2009/09/12/simplifying-lazylinq/</link>
		<comments>http://solutionizing.net/2009/09/12/simplifying-lazylinq/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 05:00:21 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ILazyContext]]></category>
		<category><![CDATA[ILazyQueryable]]></category>
		<category><![CDATA[LazyLinq]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=651</guid>
		<description><![CDATA[This is the fourth in a series of posts on LazyLinq, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:

Introducing LazyLinq: Overview
Introducing LazyLinq: Internals
Introducing LazyLinq: Queryability
Simplifying LazyLinq

Introducing LazyLinq: Lazy DataContext

As I was iterating on the proof of concept for LazyLinq, I always wanted to get rid of the TQuery type [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=651&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is the fourth in a series of posts on <a href="http://lazylinq.codeplex.com/">LazyLinq</a>, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:</p>
<ol>
<li><a href="http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/">Introducing LazyLinq: Overview</a></li>
<li><a href="http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/">Introducing LazyLinq: Internals</a></li>
<li><a href="http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/">Introducing LazyLinq: Queryability</a></li>
<li><strong>Simplifying LazyLinq<br />
</strong></li>
<li>Introducing LazyLinq: Lazy DataContext</li>
</ol>
<p>As I was iterating on the proof of concept for LazyLinq, I always wanted to get rid of the <code>TQuery</code> type parameter. I thought I needed it to distinguish between ordered and unordered wrapped queries, but it just felt messy. The underlying provider mechanism didn&#8217;t need it, so why should I?</p>
<p>Well after taking a closer look at the SQL query provider, I figured out how to eliminate it. The object of inspiration is <code>System.Data.Linq.DataQuery&lt;T&gt;</code>, defined as follows:</p>
<pre>internal sealed class DataQuery&lt;T&gt; :
    IOrderedQueryable&lt;T&gt;, IQueryable&lt;T&gt;,
    IOrderedQueryable, IQueryable,
    IEnumerable&lt;T&gt;, IEnumerable,
    IQueryProvider,
    IListSource</pre>
<p>The key was realizing that <code>IOrderedQueryable&lt;&gt;</code> and <code>ILazyOrderedQueryable&lt;&gt;</code> don&#8217;t actually do anything. Implementation-wise, they&#8217;re just <code>IQueryable&lt;&gt;</code> or <code>ILazyQueryable&lt;&gt;</code> with an extra interface on top. It&#8217;s only on the design side that it actually matters, essentially providing a hook for additional ordering with <code>ThenBy</code>. In LINQ to SQL&#8217;s case, that means supporting orderability is as simple as specifying that the query object is both <code>IQueryable&lt;&gt;</code> and <code>IOrderedQueryable&lt;&gt;</code>.</p>
<p>So how does this revelation simplify Lazy LINQ? First, it allows us to remove <code>TQuery</code> from the interfaces:</p>
<pre>    public interface ILazyContext&lt;TContext&gt; : IDisposable
    {
        TContext Context { get; }
        ILazyQueryable&lt;TContext, TResult&gt;
            CreateQuery&lt;TResult&gt;(Func&lt;TContext, IQueryable&lt;TResult&gt;&gt; queryBuilder);
        TResult Execute&lt;TResult&gt;(Func&lt;TContext, TResult&gt; action);
    }

    public interface ILazyQueryable&lt;TContext, TSource&gt; : IQueryable&lt;TSource&gt;
    {
        ILazyContext&lt;TContext&gt; Context { get; }
        Func&lt;TContext, IQueryable&lt;TSource&gt;&gt; QueryBuilder { get; }
    }

    public interface ILazyOrderedQueryable&lt;TContext, TSource&gt;
        : ILazyQueryable&lt;TContext, TSource&gt;, IOrderedQueryable&lt;TSource&gt;
    { }</pre>
<p>Note that we can also eliminate <code>ILazyContext.CreateOrderedQuery()</code>, instead assuming that <code>CreateQuery()</code> will return something that can be treated as <code>ILazyOrderedQueryable&lt;&gt;</code> as necessary.</p>
<p>For the concrete implementations, we take the cue from <code>DataQuery&lt;T&gt;</code>, letting <code>LazyQueryableImpl</code> implement <code>ILazyOrderedQueryable&lt;&gt;</code> so we can eliminate <code>LazyOrderedQueryableImpl</code>:</p>
<pre>    class LazyQueryableImpl&lt;TContext, TSource&gt;
        : ILazyQueryable&lt;TContext, TSource&gt;, ILazyOrderedQueryable&lt;TContext, TSource&gt;
    {
        // Implementation doesn't change
    }</pre>
<p>Finally, our sorting query operations will look more like their counterparts in <code>System.Linq.Queryable</code>, casting the result of <code>CreateQuery()</code> to <code>ILazyOrderedQueryable&lt;&gt;</code>. To keep things readable, we&#8217;ll split our <code>CreateOrderedQuery&lt;&gt;</code> helper into separate versions for <code>OrderBy</code> and <code>ThenBy</code>. Note how the types of <code>queryOperation</code> map to the usage of <code>OrderBy</code> (unordered to ordered) and <code>ThenBy</code> (ordered to ordered):</p>
<pre>        private static ILazyOrderedQueryable&lt;TContext, TResult&gt;
            CreateOrderByQuery&lt;TSource, TContext, TResult&gt;(
                this ILazyQueryable&lt;TContext, TSource&gt; source,
                Func&lt;IQueryable&lt;TSource&gt;, IOrderedQueryable&lt;TResult&gt;&gt; queryOperation
            )
        {
            return (ILazyOrderedQueryable&lt;TContext, TResult&gt;) source.Context.CreateQuery&lt;TResult&gt;(
               context =&gt; queryOperation(source.QueryBuilder(context)));
        }

        private static ILazyOrderedQueryable&lt;TContext, TResult&gt;
            CreateThenByQuery&lt;TSource, TContext, TResult&gt;(
                this ILazyQueryable&lt;TContext, TSource&gt; source,
                Func&lt;IOrderedQueryable&lt;TSource&gt;, IOrderedQueryable&lt;TResult&gt;&gt; queryOperation
            )
        {
            return (ILazyOrderedQueryable&lt;TContext, TResult&gt;) source.Context.CreateQuery&lt;TResult&gt;(
               context =&gt; queryOperation((IOrderedQueryable&lt;TSource&gt;) source.QueryBuilder(context)));
        }</pre>
<p>Removing <code>TQuery</code> from the query operators is left as an exercise for the reader. Or you can just <a title="Lazy LINQ Changeset 26863" href="http://lazylinq.codeplex.com/">get the source on CodePlex</a>.</p>
<h3>A Note on <code>IOrderedEnumerable&lt;&gt;</code></h3>
<p>Having taken advantage of how LINQ to IQueryable handles orderability, it&#8217;s worth pointing out that LINQ to Objects uses a different approach, specifying new behavior in <code>IOrderedEnumerable&lt;&gt;</code> that is used to support multiple sort criteria:</p>
<pre>public interface IOrderedEnumerable&lt;TElement&gt; : IEnumerable&lt;TElement&gt;, IEnumerable
{
    IOrderedEnumerable&lt;TElement&gt;
        CreateOrderedEnumerable&lt;TKey&gt;(
            Func&lt;TElement, TKey&gt; keySelector,
            IComparer&lt;TKey&gt; comparer, bool descending);
}</pre>
 Tagged: ILazyContext, ILazyQueryable, LazyLinq <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/651/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=651&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/ciGKKjISrzk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/09/12/simplifying-lazylinq/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing LazyLinq: Queryability</title>
		<link>http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/</link>
		<comments>http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 02:34:39 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ILazyQueryable]]></category>
		<category><![CDATA[LazyLinq]]></category>
		<category><![CDATA[Queryable]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=631</guid>
		<description><![CDATA[This is the third in a series of posts on LazyLinq, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:

Introducing LazyLinq: Overview
Introducing LazyLinq: Internals
Introducing LazyLinq: Queryability
Simplifying LazyLinq
Introducing LazyLinq: Lazy DataContext

Having defined the LazyLinq interfaces and provided concrete implementations, we&#8217;re left to provide support for the standard query operators.
Learning from Queryable
Before [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=631&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is the third in a series of posts on <a href="http://lazylinq.codeplex.com/">LazyLinq</a>, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:</p>
<ol>
<li><a href="http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/">Introducing LazyLinq: Overview</a></li>
<li><a href="http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/">Introducing LazyLinq: Internals</a></li>
<li><strong>Introducing LazyLinq: Queryability</strong></li>
<li><a href="http://solutionizing.net/2009/09/12/simplifying-lazylinq/">Simplifying LazyLinq</a></li>
<li>Introducing LazyLinq: Lazy DataContext</li>
</ol>
<p>Having defined the LazyLinq interfaces and provided concrete implementations, we&#8217;re left to provide support for the standard query operators.</p>
<h2>Learning from Queryable</h2>
<p>Before we try to query <code>ILazyQueryable</code>, it&#8217;s instructive to look at how <code>System.Linq.Queryable</code> works. There are essentially three types of operators on <code>IQueryable&lt;&gt;</code>:</p>
<ul>
<li>Deferred queries returning <code>IQueryable&lt;&gt;</code>: Select, Where, etc.</li>
<li>Deferred query returning <code>IOrderedQueryable&lt;&gt;</code>: OrderBy, OrderByDescending, ThenBy, ThenByDescending</li>
<li>Everything else: Aggregate, Count, First, etc.</li>
</ul>
<p>Reflecting <code>Queryable.Select</code>, modulo error checking, we see the following:</p>
<pre>public static IQueryable&lt;TResult&gt; Select&lt;TSource, TResult&gt;(
    this IQueryable&lt;TSource&gt; source, Expression&lt;Func&lt;TSource, TResult&gt;&gt; selector)
{
    return source.Provider
        .CreateQuery&lt;TResult&gt;(
            Expression.Call(null,
                ((MethodInfo) MethodBase.GetCurrentMethod())
                    .MakeGenericMethod(new Type[] { typeof(TSource), typeof(TResult) }),
                new Expression[] { source.Expression, Expression.Quote(selector) }));
}</pre>
<p>The <code>source</code>&#8217;s <code>Provider</code> is used to construct a new query whose expression includes the call to <code>Select</code> with the given parameters. An ordered query follows a similar pattern, trusting that the query provider will return an <code>IOrderedQueryable&lt;&gt;</code> as appropriate:</p>
<pre>public static IOrderedQueryable&lt;TSource&gt; OrderBy&lt;TSource, TKey&gt;(
    this IQueryable&lt;TSource&gt; source, Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
{
    return (IOrderedQueryable&lt;TSource&gt;) source.Provider
        .CreateQuery&lt;TSource&gt;(
            Expression.Call(null,
                ((MethodInfo) MethodBase.GetCurrentMethod())
                    .MakeGenericMethod(new Type[] { typeof(TSource), typeof(TKey) }),
                new Expression[] { source.Expression, Expression.Quote(keySelector) }));
}</pre>
<p>And finally, everything that&#8217;s not a query is handled by the provider&#8217;s <code>Execute</code> method:</p>
<pre>public static TSource First&lt;TSource&gt;(this IQueryable&lt;TSource&gt; source)
{
    return source.Provider
        .Execute&lt;TSource&gt;(
            Expression.Call(null,
                ((MethodInfo) MethodBase.GetCurrentMethod())
                    .MakeGenericMethod(new Type[] { typeof(TSource) }),
                new Expression[] { source.Expression }));
}</pre>
<h2>Querying ILazyQueryable</h2>
<p>You may have noticed that the above scenarios map rather closely to the methods provided by <code>ILazyContext</code>:</p>
<ul>
<li>
<pre>ILazyQueryable&lt;TContext, TResult, TQuery&gt;
    CreateQuery&lt;TResult, TQuery&gt;(Func&lt;TContext, TQuery&gt; queryBuilder)
    where TQuery : IQueryable&lt;TResult&gt;;</pre>
</li>
<li>
<pre>ILazyOrderedQueryable&lt;TContext, TResult, TQuery&gt;
    CreateOrderedQuery&lt;TResult, TQuery&gt;(Func&lt;TContext, TQuery&gt; queryBuilder)
    where TQuery : IOrderedQueryable&lt;TResult&gt;;</pre>
</li>
<li>
<pre>TResult Execute&lt;TResult&gt;(Func&lt;TContext, TResult&gt; action);</pre>
</li>
</ul>
<p>However, rather than expression trees we&#8217;re pushing around delegates. <code>Execute</code> seems pretty simple, so let&#8217;s start there:</p>
<pre>public static TSource First&lt;TSource, TContext, TQuery&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    Func&lt;TContext, TResult&gt; action = context =&gt; ???;
    return source.Context.Execute(action);
}</pre>
<p>So our source has a <code>Context</code>, which knows how to <code>Execute</code> an action from <code>context</code> to some result. To find that result, we need to leverage the other property of source: <code>QueryBuilder</code>. Recalling that <code>QueryBuilder</code> is a function from <code>TContext</code> to <code>TQuery</code>, and that <code>TQuery</code> is an <code>IQueryable&lt;TSource&gt;</code>, we see something on which we can execute <code>Queryable.First</code>:</p>
<pre>public static TSource First&lt;TSource, TContext, TQuery&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    Func&lt;TContext, TResult&gt; action =
        context =&gt; source.QueryBuilder(context).First();
    return source.Context.Execute(action);
}</pre>
<p>Now seeing as we have dozens of methods to implement like this, it seems an opportune time for a bit of eager refactoring. Recognizing that the only variance is the method call on the <code>IQueryable</code>, let&#8217;s extract an extension method that does everything else:</p>
<pre>private static TResult Execute&lt;TSource, TContext, TResult, TQuery&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source,
        Func&lt;TQuery, TResult&gt; queryOperation
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    return source.Context.Execute(
        context =&gt; queryOperation(source.QueryBuilder(context)));
}</pre>
<p>From there, additional lazy operators are just a lambda expression away:</p>
<pre>public static TSource First&lt;TSource, TContext, TQuery&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    return source.Execute(q =&gt; q.First());
}

public static TAccumulate Aggregate&lt;TContext, TSource, TQuery, TAccumulate&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source,
        TAccumulate seed, Expression&lt;Func&lt;TAccumulate, TSource, TAccumulate&gt;&gt; func
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    return source.Execute(q =&gt; q.Aggregate(seed, func));
}</pre>
<p>And now having done the hard part (finding an <code>IQueryable</code>), we can translate that understanding to make similar helpers for queries:</p>
<pre>private static ILazyQueryable&lt;TContext, TResult, IQueryable&lt;TResult&gt;&gt;
    CreateQuery&lt;TSource, TContext, TQuery, TResult&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source,
        Func&lt;TQuery, IQueryable&lt;TResult&gt;&gt; queryOperation
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    return source.Context.CreateQuery&lt;TResult, IQueryable&lt;TResult&gt;&gt;(
        context =&gt; queryOperation(source.QueryBuilder(context)));
}

private static ILazyOrderedQueryable&lt;TContext, TResult, IOrderedQueryable&lt;TResult&gt;&gt;
    CreateOrderedQuery&lt;TSource, TContext, TQuery, TResult&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source,
        Func&lt;TQuery, IOrderedQueryable&lt;TResult&gt;&gt; queryOperation
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    return source.Context.CreateOrderedQuery&lt;TResult, IOrderedQueryable&lt;TResult&gt;&gt;(
        context =&gt; queryOperation(source.QueryBuilder(context)));
}</pre>
<p>With similarly trivial query operator implementations:</p>
<pre>public static ILazyQueryable&lt;TContext, TResult, IQueryable&lt;TResult&gt;&gt;
    Select&lt;TContext, TSource, TQuery, TResult&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source,
        Expression&lt;Func&lt;TSource, TResult&gt;&gt; selector
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    return source.CreateQuery(q =&gt; q.Select(selector));
}

public static ILazyOrderedQueryable&lt;TContext, TSource, IOrderedQueryable&lt;TSource&gt;&gt;
    OrderBy&lt;TContext, TSource, TQuery, TKey&gt;(
        this ILazyQueryable&lt;TContext, TSource, TQuery&gt; source,
        Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector
    ) where TQuery : IQueryable&lt;TSource&gt;
{
    return source.CreateOrderedQuery(q =&gt; q.OrderBy(keySelector));
}</pre>
<p>And the end result:</p>
<p><img title="LazyLinq.First" src="http://solutionizing.files.wordpress.com/2009/08/lazylinq-first.png?w=739&#038;h=226" alt="LazyLinq.First" width="739" height="226" /></p>
 Tagged: ILazyQueryable, LazyLinq, Queryable <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/631/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=631&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/yUz5tUROAVk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>

		<media:content url="http://solutionizing.files.wordpress.com/2009/08/lazylinq-first.png" medium="image">
			<media:title type="html">LazyLinq.First</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing LazyLinq: Internals</title>
		<link>http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/</link>
		<comments>http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 05:24:20 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ILazyContext]]></category>
		<category><![CDATA[ILazyQueryable]]></category>
		<category><![CDATA[LazyLinq]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=615</guid>
		<description><![CDATA[This is the second in a series of posts on LazyLinq, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:

Introducing LazyLinq: Overview
Introducing LazyLinq: Internals
Introducing LazyLinq: Queryability
Simplifying LazyLinq
Introducing LazyLinq: Lazy DataContext

My first post introduced the three interfaces that LazyLinq provides. Next, we get to implement them.
Implementing ILazyQueryable
First, the interface:
   [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=615&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is the second in a series of posts on <a href="http://lazylinq.codeplex.com/">LazyLinq</a>, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:</p>
<ol>
<li><a href="http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/">Introducing LazyLinq: Overview</a></li>
<li><strong>Introducing LazyLinq: Internals</strong></li>
<li><a href="http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/">Introducing LazyLinq: Queryability</a></li>
<li><a href="http://solutionizing.net/2009/09/12/simplifying-lazylinq/">Simplifying LazyLinq</a></li>
<li>Introducing LazyLinq: Lazy DataContext</li>
</ol>
<p>My first post introduced the three interfaces that LazyLinq provides. Next, we get to implement them.</p>
<h2>Implementing ILazyQueryable</h2>
<p>First, the interface:</p>
<pre>    public interface ILazyQueryable&lt;TContext, TSource, TQuery&gt;
        : IQueryable&lt;TSource&gt;
        where TQuery : IQueryable&lt;TSource&gt;
    {
        ILazyContext&lt;TContext&gt; Context { get; }
        Func&lt;TContext, TQuery&gt; QueryBuilder { get; }
    }</pre>
<p>We&#8217;ll start simple with an implicit implementation of the interface and a trivial constructor:</p>
<pre>    class LazyQueryableImpl&lt;TContext, TSource, TQuery&gt;
            : ILazyQueryable&lt;TContext, TSource, TQuery&gt;
            where TQuery : IQueryable&lt;TSource&gt;
    {
            public ILazyContext&lt;TContext&gt; Context { get; private set; }
            public Func&lt;TContext, TQuery&gt; QueryBuilder { get; private set; }

            internal LazyQueryableImpl(ILazyContext&lt;TContext&gt; deferredContext, Func&lt;TContext, TQuery&gt; queryBuilder)
            {
                if (deferredContext == null) throw new ArgumentNullException("deferredContext");
                if (queryBuilder == null) throw new ArgumentNullException("queryBuilder");

                Context = deferredContext;
                QueryBuilder = queryBuilder;
            }</pre>
<p>Next, a lazy-loaded query built from our lazy context:</p>
<pre>            protected TQuery Query
            {
                get
                {
                    if (query == null)
                    {
                        query = QueryBuilder(Context.Context);
                        if (query == null)
                            throw new InvalidOperationException("Query built as null.");
                    }
                    return query;
                }
            }</pre>
<p>And the internals of managing <code>Context</code>, which implements <code>IDisposable</code>:</p>
<pre>            private void Dispose()
            {
                Context.Dispose();
                query = default(TQuery);
            }

            private IEnumerator&lt;TSource&gt; GetEnumerator()
            {
                try
                {
                    foreach (var i in Query)
                        yield return i;
                }
                finally
                {
                    Dispose();
                }
            }</pre>
<p>Since <code>Query</code> depends on <code>Context</code>, once <code>Context</code> is disposed we need to reset <code>Query</code> so a new one can be built (if possible). Note that we use an iterator here to return an <code>IEnumerator&lt;TSource&gt;</code>, rather than the usual <code>IEnumerable&lt;&gt;</code>.</p>
<p>Finally, we&#8217;ll close out by explicitly implementing <code>IQueryable</code>:</p>
<pre>            IEnumerator&lt;TSource&gt; IEnumerable&lt;TSource&gt;.GetEnumerator()
            {
                return GetEnumerator();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }

            Type IQueryable.ElementType
            {
                get { return Query.ElementType; }
            }

            Expression IQueryable.Expression
            {
                get { return Query.Expression; }
            }

            IQueryProvider IQueryable.Provider
            {
                get { return Query.Provider; }
            }
        }</pre>
<p>If this seemed relatively simple, you&#8217;re right. We&#8217;re just building a lazy-loaded <code>Query</code> proxy, with a bit of plumbing to clean up our <code>Context</code>.</p>
<h2>Implementing ILazyOrderedQueryable</h2>
<p>Not very exciting, but for completeness:</p>
<pre>        public interface ILazyOrderedQueryable&lt;TContext, TSource, TQuery&gt;
            : ILazyQueryable&lt;TContext, TSource, TQuery&gt;, IOrderedQueryable&lt;TSource&gt;
            where TQuery : IOrderedQueryable&lt;TSource&gt;
        { }

        class LazyOrderedQueryableImpl&lt;TContext, TSource, TQuery&gt;
                : LazyQueryableImpl&lt;TContext, TSource, TQuery&gt;, ILazyOrderedQueryable&lt;TContext, TSource, TQuery&gt;
                where TQuery : IOrderedQueryable&lt;TSource&gt;
        {
            internal LazyOrderedQueryableImpl(ILazyContext&lt;TContext&gt; lazyContext, Func&lt;TContext, TQuery&gt; queryBuilder)
                : base(lazyContext, queryBuilder)
            {
            }
        }</pre>
<h2>LazyQueryable Factory</h2>
<p>Consumers of this API should never need to know about these implementation details, so we can hide them behind a factory class:</p>
<pre>        public static class LazyQueryable
        {
            public static ILazyQueryable&lt;TContext, TResult, TQuery&gt; CreateQuery&lt;TContext, TResult, TQuery&gt;(
                ILazyContext&lt;TContext&gt; context, Func&lt;TContext, TQuery&gt; queryBuilder)
                where TQuery : IQueryable&lt;TResult&gt;
            {
                return new LazyQueryableImpl&lt;TContext, TResult, TQuery&gt;(context, queryBuilder);
            }
            public static ILazyOrderedQueryable&lt;TContext, TResult, TQuery&gt; CreateOrderedQuery&lt;TContext, TResult, TQuery&gt;(
                ILazyContext&lt;TContext&gt; context, Func&lt;TContext, TQuery&gt; queryBuilder)
                where TQuery : IOrderedQueryable&lt;TResult&gt;
            {
                return new LazyOrderedQueryableImpl&lt;TContext, TResult, TQuery&gt;(context, queryBuilder);
            }
        }</pre>
<h2>Implementing ILazyContext</h2>
<p>Again, we&#8217;ll start with the interface:</p>
<pre>        public interface ILazyContext&lt;TContext&gt; : IDisposable
        {
            TContext Context { get; }

            ILazyQueryable&lt;TContext, TResult, TQuery&gt;
                CreateQuery&lt;TResult, TQuery&gt;(Func&lt;TContext, TQuery&gt; queryBuilder)
                where TQuery : IQueryable&lt;TResult&gt;;

            ILazyOrderedQueryable&lt;TContext, TResult, TQuery&gt;
                CreateOrderedQuery&lt;TResult, TQuery&gt;(Func&lt;TContext, TQuery&gt; queryBuilder)
                where TQuery : IOrderedQueryable&lt;TResult&gt;;

            TResult Execute&lt;TResult&gt;(Func&lt;TContext, TResult&gt; action);
        }</pre>
<p>Now we can start fulfilling our requirements:</p>
<h3>1. Lazily expose the Context.</h3>
<pre>        class LazyContextImpl&lt;TContext&gt; : ILazyContext&lt;TContext&gt;, IDisposable
        {
            public Func&lt;TContext&gt; ContextBuilder { get; private set; }

            private TContext context;
            public TContext Context
            {
                get
                {
                    if (context == null)
                    {
                        context = ContextBuilder();
                        if (context == null)
                            throw new InvalidOperationException("Context built as null.");
                    }
                    return context;
                }
            }</pre>
<h3>2. Produce lazy wrappers to represent queries retrieved from a context by a delegate.</h3>
<pre>            public ILazyQueryable&lt;TContext, TResult, TQuery&gt; CreateQuery&lt;TResult, TQuery&gt;(
                Func&lt;TContext, TQuery&gt; queryBuilder)
                where TQuery : IQueryable&lt;TResult&gt;
            {
                return LazyQueryable.CreateQuery&lt;TContext, TResult, TQuery&gt;(this, queryBuilder);
            }

            public ILazyOrderedQueryable&lt;TContext, TResult, TQuery&gt; CreateOrderedQuery&lt;TResult, TQuery&gt;(
                Func&lt;TContext, TQuery&gt; queryBuilder)
                where TQuery : IOrderedQueryable&lt;TResult&gt;
            {
                return LazyQueryable.CreateOrderedQuery&lt;TContext, TResult, TQuery&gt;(this, queryBuilder);
            }</pre>
<h3>3. Execute an action on the context.</h3>
<p>There are two ways to &#8220;complete&#8221; a query, and we need to clean up context after each. The first was after enumeration, implemented above. The second is on execute, implemented here:</p>
<pre>            public TResult Execute&lt;TResult&gt;(Func&lt;TContext, TResult&gt; expression)
            {
                try
                {
                    return expression(Context);
                }
                finally
                {
                    Dispose();
                }
            }</pre>
<h3>4. Ensure the context is disposed as necessary.</h3>
<p>We don&#8217;t require that <code>TContext</code> is <code>IDisposable</code>, but we need to handle if it is. We also clear context to support reuse.</p>
<pre>            public void Dispose()
            {
                var disposable = context as IDisposable;
                if (disposable != null)
                    disposable.Dispose();

                context = default(TContext);
            }</pre>
<h3>Constructors</h3>
<p>With our requirements met, we just need a way to create our context. We provide two options:</p>
<pre>            internal LazyContextImpl(TContext context) : this(() =&gt; context) { }

            internal LazyContextImpl(Func&lt;TContext&gt; contextBuilder)
            {
                if (contextBuilder == null) throw new ArgumentNullException("contextBuilder");

                ContextBuilder = contextBuilder;
            }</pre>
<p>The former wraps an existing <code>TContext</code> instance in a closure, meaning every time <code>ContextBuilder</code> is called it returns the same instance. The latter accepts any delegate that returns a <code>TContext</code>. The most common such delegate would be a simple instantiation: <code>() =&gt; new MyDataContext()</code>.</p>
<p>It should be clear now why we would want to clear our context on dispose. If <code>ContextBuilder</code> returns a new context instance each time, it&#8217;s perfectly safe to discard of the old (disposed) context to trigger the creation of a new one. Conversely, if the builder returns a single instance, using the context after disposal would trigger an <code>ObjectDisposedException</code> or something similar.</p>
<h2>LazyContext Factory</h2>
<p>For consistency, we should also provide factory methods to hide this specific implementation:</p>
<pre>            public static class LazyContext
            {
                public static ILazyContext&lt;T&gt; Create&lt;T&gt;(T context)
                {
                    return new LazyContextImpl&lt;T&gt;(context);
                }
                public static ILazyContext&lt;T&gt; Create&lt;T&gt;(Func&lt;T&gt; contextBuilder)
                {
                    return new LazyContextImpl&lt;T&gt;(contextBuilder);
                }
            }</pre>
<h2>Lazy Extensions</h2>
<p>And last, but certainly not least, we&#8217;re ready to reimplement our <code>Use()</code> extension methods:</p>
<pre>    public static class Lazy
    {
        public static ILazyContext&lt;TContext&gt; Use&lt;TContext&gt;(this TContext @this)
        {
            return LazyContext.Create&lt;TContext&gt;(@this);
        }

        public static ILazyContext&lt;TContext&gt; Use&lt;TContext&gt;(this Func&lt;TContext&gt; @this)
        {
            return LazyContext.Create&lt;TContext&gt;(@this);
        }
    }</pre>
<p>With several usage possibilities:</p>
<pre>    var r1 = from x in new MyDataContext().Use() ...;

    Func&lt;MyDataContext&gt; f1 = () =&gt; new MyDataContext();
    var r2 = from x in f1.Use() ...;

    var r3 = from x in new Func&lt;MyDataContext&gt;(() =&gt; new MyDataContext()).Use() ...;

    var r4 = from x in Lazy.Use(() =&gt; new MyDataContext()) ...;</pre>
<p>Or maybe we can make it even easier. Maybe&#8230;</p>
 Tagged: ILazyContext, ILazyQueryable, LazyLinq <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/615/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=615&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/gx0iSUvDrKA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing LazyLinq: Overview</title>
		<link>http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/</link>
		<comments>http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 18:58:03 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[DataContext]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[LazyLinq]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=604</guid>
		<description><![CDATA[This is the first in a series of posts on LazyLinq, a wrapper to support lazy initialization and deferred disposal of a LINQ query context, including LINQ to SQL&#8217;s DataContext:

Introducing LazyLinq: Overview
Introducing LazyLinq: Internals
Introducing LazyLinq: Queryability
Simplifying LazyLinq
Introducing LazyLinq: Lazy DataContext

Motivation
I recently posted an approach to dealing with IDisposable objects and LINQ. In the comments at [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=604&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is the first in a series of posts on <a href="http://lazylinq.codeplex.com/">LazyLinq</a>, a wrapper to support lazy initialization and deferred disposal of a LINQ query context, including LINQ to SQL&#8217;s <a title="DataContext Class (System.Data.Linq)" href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx"><code>DataContext</code></a>:</p>
<ol>
<li><strong>Introducing LazyLinq: Overview</strong></li>
<li><a href="http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/">Introducing LazyLinq: Internals</a></li>
<li><a href="http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/">Introducing LazyLinq: Queryability</a></li>
<li><a href="http://solutionizing.net/2009/09/12/simplifying-lazylinq/">Simplifying LazyLinq</a></li>
<li>Introducing LazyLinq: Lazy DataContext</li>
</ol>
<h2>Motivation</h2>
<p>I recently posted <a title="Using IDisposables with LINQ" href="http://solutionizing.net/2009/07/23/using-idisposables-with-linq/">an approach</a> to dealing with <code>IDisposable</code> objects and LINQ. In the <a title="Using IDisposables with LINQ" href="http://www.lostechies.com/blogs/dahlbyk/archive/2009/07/23/using-idisposables-with-linq.aspx#comments">comments</a> at LosTechies, <a href="http://blogger.forgottenskies.com/">Steve Gentile</a> mentioned that my <code>IQueryable</code> example didn&#8217;t actually compile:</p>
<pre>IQueryable&lt;MyType&gt; MyFunc(string myValue)
{
    return from dc in new MyDataContext().Use()
           from row in dc.MyTable
           where row.MyField == myValue
           select row;
}</pre>
<p>Steve suggested using <code>AsQueryable()</code> on the result of the query, which does indeed fix the build. However, the purpose of returning an <code>IQueryable</code> is that it would allow us to perform additional query operations using the original query provider. Since the query result isn&#8217;t <code>IQueryable</code>, <code>AsQueryable()</code> will use a query provider based on LINQ to Objects, with an additional performance penalty to compile the expression trees into IL.</p>
<p>Even worse, because <code>Use()</code> is returning an <code>IEnumerable&lt;T&gt;</code> the entire query is actually executed with LINQ to Objects. Even though <code>dc.MyTable</code> is <code>IQueryable</code>, the translated query treats it as a simple <code>IEnumerable</code>, essentially performing a <code>SELECT *</code> before executing all query operations on entity objects in memory. It should go without saying that this is less than ideal.</p>
<h2>Introducing LazyLinq</h2>
<p>After several iterations, I think I have a better solution. In this post I&#8217;ll review the architecture of the solution, with posts to follow detailing the implementation.</p>
<p>LazyLinq is implemented around three interfaces. The first serves as a deferred query context provider:</p>
<pre>    public interface ILazyContext&lt;TContext&gt; : IDisposable
    {
        TContext Context { get; }

        ILazyQueryable&lt;TContext, TResult, TQuery&gt;
            CreateQuery&lt;TResult, TQuery&gt;(Func&lt;TContext, TQuery&gt; queryBuilder)
            where TQuery : IQueryable&lt;TResult&gt;;

        ILazyOrderedQueryable&lt;TContext, TResult, TQuery&gt;
            CreateOrderedQuery&lt;TResult, TQuery&gt;(Func&lt;TContext, TQuery&gt; queryBuilder)
            where TQuery : IOrderedQueryable&lt;TResult&gt;;

        TResult Execute&lt;TResult&gt;(Func&lt;TContext, TResult&gt; action);
    }</pre>
<p>An implementer of <code>ILazyContext</code> has four responsibilities:</p>
<ol>
<li>Lazily expose the Context.</li>
<li>Produce lazy wrappers to represent queries retrieved from a context by a delegate.</li>
<li>Execute an action on the context.</li>
<li>Ensure the context is disposed as necessary.</li>
</ol>
<p>The remaining interfaces serve as lazy query wrappers, corresponding to <code>IQueryable&lt;T&gt;</code> and <code>IOrderedQueryable&lt;T&gt;</code>:</p>
<pre>    public interface ILazyQueryable&lt;TContext, TSource, TQuery&gt;
        : IQueryable&lt;TSource&gt;
        where TQuery : IQueryable&lt;TSource&gt;
    {
        ILazyContext&lt;TContext&gt; Context { get; }
        Func&lt;TContext, TQuery&gt; QueryBuilder { get; }
    }
    public interface ILazyOrderedQueryable&lt;TContext, TSource, TQuery&gt;
        : ILazyQueryable&lt;TContext, TSource, TQuery&gt;, IOrderedQueryable&lt;TSource&gt;
        where TQuery : IOrderedQueryable&lt;TSource&gt;
    { }</pre>
<p>An implementer of <code>ILazyQueryable</code> has four responsibilities:</p>
<ol>
<li>Expose the Context from which it was created.</li>
<li>Expose a delegate that represents how the deferred query is built from Context.</li>
<li>Implement IQueryable for the deferred query.</li>
<li>Ensure the context is disposed after the query is enumerated.</li>
</ol>
<p>If it seems like these interfaces don&#8217;t do much, you&#8217;re absolutely correct. As we&#8217;ll see later, the light footprint gives us considerable flexibility.</p>
<h2>LINQ to ILazyContext</h2>
<p>Defining a few interfaces is all well and good, but the real goal is to simplify working with our disposable context. What if I told you that our original use case didn&#8217;t need to change at all (other than the lazy return type)?</p>
<pre>ILazyQueryable&lt;MyType&gt; MyFunc(string myValue)
{
    return from dc in new MyDataContext().Use()
           from row in dc.MyTable
           where row.MyField == myValue
           select row;
}</pre>
<p>We can&#8217;t implement it yet, but our new <code>Use()</code> extension method will have this signature:</p>
<pre>    public static ILazyContext&lt;TContext&gt; Use&lt;TContext&gt;(this TContext @this) { ... }</pre>
<p>This is where we really start to bend LINQ against its will. As the first step in the query translation process, the compiler will translate our <code>from</code> clauses into a call to <code>SelectMany</code>. All we need to do is provide a <code>SelectMany</code> method for <code>ILazyContext</code> that the compiler will find acceptable:</p>
<pre>    public static ILazyQueryable&lt;TContext, TResult, IQueryable&lt;TResult&gt;&gt; SelectMany&lt;TContext, TCollection, TResult&gt;(
        this ILazyContext&lt;TContext&gt; lazyContext,
        Expression&lt;Func&lt;TContext, IQueryable&lt;TCollection&gt;&gt;&gt; collectionSelector,
        Expression&lt;Func&lt;TContext, TCollection, TResult&gt;&gt; resultSelector)
    {</pre>
<p>The method signature is a slight variation from the corresponding overload of <a href="http://msdn.microsoft.com/en-us/library/bb549040.aspx"><code>Queryable.SelectMany()</code></a>, changed to require that <code>collectionSelector</code> returns an <code>IQueryable</code> that we can defer. If it doesn&#8217;t, the compiler will complain:</p>
<blockquote><p>An expression of type &#8216;System.Collections.Generic.IEnumerable&lt;int&gt;&#8217; is not allowed in a subsequent from clause in a query expression with source type &#8216;Solutionizing.Linq.Test.MyDataContext&lt;Solutionizing.Linq.Test.MyDataContext&gt;&#8217;.  Type inference failed in the call to &#8216;SelectMany&#8217;.</p></blockquote>
<p>Now that we&#8217;ve hijacked the query, we can control the rest of the translation process with the returned <code>ILazyQueryable</code>. Recalling that our <code>ILazyContext</code> knows how to make an <code>ILazyQueryable</code>, we just need to give it a <code>QueryBuilder</code> delegate:</p>
<pre>        return lazyContext.CreateQuery&lt;TResult, IQueryable&lt;TResult&gt;&gt;(context =&gt;
            {
                Func&lt;TContext, IQueryable&lt;TCollection&gt;&gt; getQueryFromContext = collectionSelector.Compile();
                IQueryable&lt;TCollection&gt; query = getQueryFromContext(context);

                ParameterExpression rangeParameter = resultSelector.Parameters[1];
                InvocationExpression invoke = Expression.Invoke(resultSelector, Expression.Constant(context), rangeParameter);
                Expression&lt;Func&lt;TCollection, TResult&gt;&gt; selector = Expression.Lambda&lt;Func&lt;TCollection, TResult&gt;&gt;(invoke, rangeParameter);

                return query.Select(selector);
            });
    }</pre>
<p>This is pretty dense, so let&#8217;s walk through it:</p>
<ol>
<li>Our lambda expression&#8217;s <code>context</code> parameter represents the <code>MyDataContext</code> that will be passed in eventually.</li>
<li>We&#8217;re going to manipulate the expression trees passed into the method, which will look something like this:
<ul>
<li><strong><code>collectionSelector</code>:</strong> <code>dc =&gt; dc.MyTable</code></li>
<li><strong><code>resultSelector</code>:</strong> <code>(dc, row) =&gt; new { dc = dc, row = row }</code></li>
</ul>
</li>
<li>Compiling <code>collectionSelector</code> produces a delegate we can invoke on context to get an <code>IQueryable&lt;TCollection&gt;</code>—<code>context.MyTable</code>, in this case.</li>
<li>Before we can use <code>resultSelector</code> on <code>MyTable</code>, we need to wrap it in a lambda expression to eliminate its first parameter.:
<ol>
<li>Save the second parameter (<code>row</code>) to use later.</li>
<li>Create a new invocation expression that will represent calling <code>resultSelector</code> with the current <code>context</code> and our saved <code>row</code> parameter.</li>
<li>Create a new lambda expression that will accept that same <code>row</code> parameter  and return the invocation expression.</li>
</ol>
</li>
<li>The resulting <code>selector</code>, of type <code>Expression&lt;Func&lt;TCollection, TResult&gt;&gt;</code>, can then be passed to <code>query.Select()</code> which happily returns the desired <code>IQueryable&lt;TResult&gt;</code>.</li>
</ol>
<p>Essentially we&#8217;re pretending that the <code>SelectMany</code> call is just a <code>Select</code> call on the <code>IQueryable&lt;TCollection&gt;</code> generated by <code>collectionSelector</code>, all wrapped in a lazy query.</p>
<p>Hopefully this overview has piqued your interest. Next time we&#8217;ll look at a base implementation of the interfaces.</p>
 Tagged: DataContext, Expression Trees, LazyLinq <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/604/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/604/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/604/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/604/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/604/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/604/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/604/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/604/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/604/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/604/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=604&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/Ioj9IvyuB20" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Using IDisposables with LINQ</title>
		<link>http://solutionizing.net/2009/07/23/using-idisposables-with-linq/</link>
		<comments>http://solutionizing.net/2009/07/23/using-idisposables-with-linq/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 08:28:29 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Object Model]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[AsSafeEnumerable]]></category>
		<category><![CDATA[IDisposable]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to SQL]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=599</guid>
		<description><![CDATA[Objects that implement IDisposable are everywhere. The interface even gets its own language features (C#, VB, F#). However, LINQ throws a few wrenches into things:

LINQ&#8217;s query syntax depends on expressions; using blocks are statements.
When querying a sequence of IDisposable objects, there&#8217;s no easy way to ensure disposal after each element has been consumed.
Returning deferred queries [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=599&subd=solutionizing&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Objects that implement <code>IDisposable</code> are everywhere. The interface even gets its own language features (<a title="using Statement (C# Reference)" href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx">C#</a>, <a title="Using Statement (Visual Basic)" href="http://msdn.microsoft.com/en-us/library/htd05whh.aspx">VB</a>, <a title="Resource Management (F#)" href="http://msdn.microsoft.com/en-us/library/dd233240(VS.100).aspx">F#</a>). However, LINQ throws a few wrenches into things:</p>
<ol>
<li>LINQ&#8217;s query syntax depends on expressions; <code>using</code> blocks are statements.</li>
<li>When querying a sequence of <code>IDisposable</code> objects, there&#8217;s no easy way to ensure disposal after each element has been consumed.</li>
<li>Returning deferred queries from within a <code>using</code> statement is often desired, but fails spectacularly.</li>
</ol>
<p>There are possible work-arounds for each issue&#8230;</p>
<ol>
<li>Put the using statement in a method (named or anonymous) that is called from the query. See also: <a href="http://solutionizing.net/2009/02/20/thinking-functional-using/">Thinking Functional: Using</a>.</li>
<li>Use a method that creates a dispose-safe iterator of the sequence, like <a title="LINQ for SPWebCollection Revisited: AsSafeEnumerable" href="http://solutionizing.net/2009/01/05/linq-for-spwebcollection-revisited-assafeenumerable/">AsSafeEnumerable()</a>.</li>
<li>Refactor the method to inject the <code>IDisposable</code> dependency, as shown in the first part of Marc&#8217;s answer <a title="How does LINQ defer execution when in a using statement" href="http://stackoverflow.com/questions/456691/how-does-linq-defer-execution-when-in-a-using-statement/456698#456698">here</a>.</li>
</ol>
<p>But, as you might have guessed, I would like to propose a better solution. The code is really complex, so bear with me:</p>
<pre class="code">public static IEnumerable&lt;T&gt; Use&lt;T&gt;(this T obj) where T : IDisposable
{
    try
    {
        yield return obj;
    }
    finally
    {
        if (obj != null)
            obj.Dispose();
    }
}</pre>
<p>That&#8217;s it. We&#8217;re turning our <code>IDisposable</code> object into a single-element sequence. The trick is that the C# compiler will build an iterator for us that properly handles the <code>finally</code> clause, ensuring that our object will be disposed. It might be helpful to set a breakpoint on the <code>finally</code> clause to get a better idea what&#8217;s happening.</p>
<p>So how can this simple method solve all our problems? First up: &#8220;using&#8221; a <code>FileStream</code> object created in a LINQ query:</p>
<pre>var lengths = from path in myFiles
              from fs in File.OpenRead(path).Use()
              select new { path, fs.Length };</pre>
<p>Since the result of <code>Use()</code> is a single-element sequence, we can think of <code>from fs in something.Use()</code> as an assignment of that single value, <code>something</code>, to <code>fs</code>. In fact, it&#8217;s really quite similar to an F# <code>use</code> binding in that it will automatically clean itself up when it goes out of scope (by its enumerator calling <code>MoveNext()</code>).</p>
<p>Next, disposing elements from a collection. I&#8217;ll use the same SharePoint problem that <code>AsSafeEnumerable()</code> solves:</p>
<pre>var webs = from notDisposed in site.AllWebs
           from web in notDisposed.Use()
           select web.Title;</pre>
<p>I find this syntax rather clumsy compared with <code>AsSafeEnumerable()</code>, but it&#8217;s there if you need it.</p>
<p>Finally, let&#8217;s defer disposal of a LINQ to SQL <code>DataContext</code> until after the deferred query is executed, as an answer to the <a title="How does LINQ defer execution when in a using statement" href="http://stackoverflow.com/questions/456691/how-does-linq-defer-execution-when-in-a-using-statement">previously-linked Stack Overflow question</a>:</p>
<pre>IQueryable&lt;MyType&gt; MyFunc(string myValue)
{
    return from dc in new MyDataContext().Use()
           from row in dc.MyTable
           where row.MyField == myValue
           select row;
}

void UsingFunc()
{
    var result = MyFunc("MyValue").OrderBy(row =&gt; row.SortOrder);
    foreach(var row in result)
    {
        //Do something
    }
}</pre>
<p>The result of <code>MyFunc</code> now owns its destiny completely. It doesn&#8217;t depend on some potentially disposed <code>DataContext</code> &#8211; it just creates one that it will dispose when it&#8217;s done. There are probably situations where you would want to share a <code>DataContext</code> rather than create one on demand (I don&#8217;t use LINQ to SQL, I just blog about it), but again it&#8217;s there if you need it.</p>
<p>I&#8217;ve only started using this approach recently, so if you have any problems with it please share.</p>
 Tagged: AsSafeEnumerable, IDisposable, LINQ, LINQ to SQL <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/599/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&blog=3982353&post=599&subd=solutionizing&ref=&feed=1" /></div><img src="http://feeds.feedburner.com/~r/SolutionizingDotNet/~4/AqlTVuzQc_E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/07/23/using-idisposables-with-linq/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&amp;d=identicon&amp;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
	</channel>
</rss>
