<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Monty's Gush</title>
	<atom:link href="http://petemontgomery.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://petemontgomery.wordpress.com</link>
	<description>Scraps of word meat in C# and F#</description>
	<lastBuildDate>Wed, 25 Jan 2012 10:54:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='petemontgomery.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Monty's Gush</title>
		<link>http://petemontgomery.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://petemontgomery.wordpress.com/osd.xml" title="Monty&#039;s Gush" />
	<atom:link rel='hub' href='http://petemontgomery.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Dynamic parallel async requests in MVC</title>
		<link>http://petemontgomery.wordpress.com/2011/05/12/dynamic-parallel-async-requests-in-mvc/</link>
		<comments>http://petemontgomery.wordpress.com/2011/05/12/dynamic-parallel-async-requests-in-mvc/#comments</comments>
		<pubDate>Thu, 12 May 2011 15:03:28 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=577</guid>
		<description><![CDATA[How to make several asynchronous requests in parallel to the same web service, when the number of such requests is dynamically determined. Thanks to AsyncControllers, it&#8217;s quite easy to make several asynchronous requests in parallel to different web services, and have MVC gather the results. A well-written example is on MSDN. Briefly, you save the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=577&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>How to make several asynchronous requests in parallel to the same web service, when the number of such requests is dynamically determined.</p>
<p>Thanks to AsyncControllers, it&#8217;s quite easy to make <strong>several</strong> asynchronous requests in parallel to <strong>different</strong> web services, and have MVC gather the results.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ee728598.aspx#performing_multiple_operations_in_parallel">A well-written example</a> is on MSDN. Briefly, you save the result of each async call into the Parameters collection of the AsyncManager like so:</p>
<pre>
AsyncManager.Parameters["<strong>headlines</strong>"] = e.Value;
...
AsyncManager.Parameters["<strong>scores</strong>"] = e.Value;
...
AsyncManager.Parameters["<strong>forecast</strong>"] = e.Value;
</pre>
<p>Your <strong>Completed</strong> method will then bind to the parameters you have named:</p>
<pre>
public ActionResult IndexCompleted(
    HeadlinesResult <strong>headlines</strong>,
    ScoresResult <strong>scores</strong>,
    ForecastResult <strong>forecast</strong>) { ... }
</pre>
<p>This is fine if you know how many requests you want to make. But what if you want to make several requests in parallel <strong>to the same web service</strong> (for example, with slightly different parameters) &mdash; but you <strong>don&#8217;t know in advance</strong> how many requests you will need to make?</p>
<p>For example, you might show the weather forecast for as many days into the future as the user requests, up to seven days, with each day requiring a separate request to the forecast service.</p>
<p>In this case you need a <strong>dynamically-sized collection</strong> of results of the same type, such as a list. Ideally, we want our Completed method to look something like this:</p>
<pre>
public ActionResult IndexCompleted(List results) { ... }
</pre>
<h2>Fist of fun</h2>
<p>However, we don&#8217;t know on which threads, or even in what order, this collection will be <strong>added to</strong> when each of the web service calls complete independently.</p>
<p>The <strong>System.Collections.Concurrent</strong> namespace gives us a more suitable type to withstand the mutation this collection will have to put up with. </p>
<p><pre class="brush: csharp;">
public class ForecastController : AsyncController
{
    public void IndexAsync(ForecastInputModel input)
    {
        var results = new ConcurrentBag&lt;ForecastResult&gt;();

        AsyncManager.Parameters[&quot;results&quot;] = results;

        foreach (var request in GetForecastRequests(input))
        {
            AsyncManager.OutstandingOperations.Increment();

            var s = new WeatherService();

            s.GetForecastCompleted += (sender, e) =&gt;
                {
                    results.Add(e.Value); // threadsafe
                    AsyncManager.OutstandingOperations.Decrement();
                };
            
            s.GetForecastAsync(request);
        }
    }

    public ActionResult IndexCompleted(ConcurrentBag&lt;ForecastResult&gt; results)
    {
        ...
    }  
 }
</pre></p>
<p> Enjoy what you saw.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f05%2f12%2fdynamic-parallel-async-requests-in-mvc%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f05%2f12%2fdynamic-parallel-async-requests-in-mvc%2f&amp;bgcolor=33CC33" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/577/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/577/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/577/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/577/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/577/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/577/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/577/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/577/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/577/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/577/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/577/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/577/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/577/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/577/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=577&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2011/05/12/dynamic-parallel-async-requests-in-mvc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f05%2f12%2fdynamic-parallel-async-requests-in-mvc%2f&#38;bgcolor=33CC33" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>A universal PredicateBuilder</title>
		<link>http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/</link>
		<comments>http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 22:45:35 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=540</guid>
		<description><![CDATA[I don&#8217;t use the famous Albahari PredicateBuilder because it doesn&#8217;t work so well with Entity Framework or the latest version of NHibernate. This is because it relies on InvocationExpressions, which aren&#8217;t supported by many query translators, and the workaround requires an unnatural call to Tomas&#8216; AsExpandable method in all your queries. A couple of years [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=540&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f02%2f10%2fa-universal-predicatebuilder%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f02%2f10%2fa-universal-predicatebuilder%2f&amp;bgcolor=33CC33" /></a></p>
<p>I don&#8217;t use the famous Albahari <a href="http://www.albahari.com/nutshell/predicatebuilder.aspx">PredicateBuilder</a> because it doesn&#8217;t work so well with Entity Framework or the latest version of NHibernate.</p>
<p>This is because it relies on <strong>InvocationExpression</strong>s, which aren&#8217;t supported by many query translators, and the workaround requires an unnatural call to <a href="http://tomasp.net/">Tomas</a>&#8216; <strong>AsExpandable</strong> method in all your queries.</p>
<p>A couple of years ago, Colin Meek on the EF team showed me how to compose predicates <a href="http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx">without using InvocationExpressions</a> and since then I&#8217;ve used my own synthesized version of PredicateBuilder, with the same API as the awesome Albahari original. </p>
<div class="highlightbox">The same API also allows a lovely point-free style of composition. Say you have a list of <strong>predicates</strong> you want to &#8220;or&#8221; together, use the standard <strong>Aggregate</strong> function like so:</p>
<p>var predicate = predicates.Aggregate(PredicateBuilder.Or);
</p></div>
<p>If you need a PredicateBuilder that works as you&#8217;d expect with Entity Framework, NHibernate&#8230; as well as Linq to SQL, here it is. (It ought to work in Silverlight too. Let me know&#8230;!)</p>
<p><pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Enables the efficient, dynamic composition of query predicates.
    /// &lt;/summary&gt;
    public static class PredicateBuilder
    {
        /// &lt;summary&gt;
        /// Creates a predicate that evaluates to true.
        /// &lt;/summary&gt;
        public static Expression&lt;Func&lt;T, bool&gt;&gt; True&lt;T&gt;() { return param =&gt; true; }

        /// &lt;summary&gt;
        /// Creates a predicate that evaluates to false.
        /// &lt;/summary&gt;
        public static Expression&lt;Func&lt;T, bool&gt;&gt; False&lt;T&gt;() { return param =&gt; false; }

        /// &lt;summary&gt;
        /// Creates a predicate expression from the specified lambda expression.
        /// &lt;/summary&gt;
        public static Expression&lt;Func&lt;T, bool&gt;&gt; Create&lt;T&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return predicate; }

        /// &lt;summary&gt;
        /// Combines the first predicate with the second using the logical &quot;and&quot;.
        /// &lt;/summary&gt;
        public static Expression&lt;Func&lt;T, bool&gt;&gt; And&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second)
        {
            return first.Compose(second, Expression.AndAlso);
        }

        /// &lt;summary&gt;
        /// Combines the first predicate with the second using the logical &quot;or&quot;.
        /// &lt;/summary&gt;
        public static Expression&lt;Func&lt;T, bool&gt;&gt; Or&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second)
        {
            return first.Compose(second, Expression.OrElse);
        }

        /// &lt;summary&gt;
        /// Negates the predicate.
        /// &lt;/summary&gt;
        public static Expression&lt;Func&lt;T, bool&gt;&gt; Not&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; expression)
        {
            var negated = Expression.Not(expression.Body);
            return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(negated, expression.Parameters);
        }

        /// &lt;summary&gt;
        /// Combines the first expression with the second using the specified merge function.
        /// &lt;/summary&gt;
        static Expression&lt;T&gt; Compose&lt;T&gt;(this Expression&lt;T&gt; first, Expression&lt;T&gt; second, Func&lt;Expression, Expression, Expression&gt; merge)
        {
            // zip parameters (map from parameters of second to parameters of first)
            var map = first.Parameters
                .Select((f, i) =&gt; new { f, s = second.Parameters[i] })
                .ToDictionary(p =&gt; p.s, p =&gt; p.f);

            // replace parameters in the second lambda expression with the parameters in the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

            // create a merged lambda expression with parameters from the first expression
            return Expression.Lambda&lt;T&gt;(merge(first.Body, secondBody), first.Parameters);
        }

        class ParameterRebinder : ExpressionVisitor
        {
            readonly Dictionary&lt;ParameterExpression, ParameterExpression&gt; map;

            ParameterRebinder(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map)
            {
                this.map = map ?? new Dictionary&lt;ParameterExpression, ParameterExpression&gt;();
            }

            public static Expression ReplaceParameters(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map, Expression exp)
            {
                return new ParameterRebinder(map).Visit(exp);
            }

            protected override Expression VisitParameter(ParameterExpression p)
            {
                ParameterExpression replacement;

                if (map.TryGetValue(p, out replacement))
                {
                    p = replacement;
                }

                return base.VisitParameter(p);
            }
        }
    }

</pre></p>
<div class="highlightbox">You&#8217;ll also need the <a href="http://msdn.microsoft.com/en-us/library/bb882521(v=vs.90).aspx">ExpressionVisitor</a> if you&#8217;re not on .NET 4.</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/540/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=540&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f02%2f10%2fa-universal-predicatebuilder%2f&#38;bgcolor=33CC33" medium="image" />
	</item>
		<item>
		<title>FromCache now supports local collections</title>
		<link>http://petemontgomery.wordpress.com/2011/01/03/fromcache-now-supports-local-collections/</link>
		<comments>http://petemontgomery.wordpress.com/2011/01/03/fromcache-now-supports-local-collections/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 18:36:17 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=453</guid>
		<description><![CDATA[A commenter recently discovered that the technique I use to generate a cache key for any IQueryable was not working properly for one of his queries. The query contained a call to List.Contains, and the contents of the list was not getting put into the cache key. The problem was that the query cache didn&#8217;t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=453&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A commenter <a href="/2008/08/07/caching-the-results-of-linq-queries/#comment-84">recently discovered</a> that the technique I use to <strong>generate a cache key</strong> for any IQueryable was not working properly for one of his queries. The query contained a call to <strong>List.Contains</strong>, and the contents of the list was not getting put into the cache key.</p>
<p>The problem was that the query cache didn&#8217;t specifically know about <strong>local collection values</strong>.</p>
<p>Local collection values can be supplied as parameters to query operators such as <strong>Contains</strong> and <strong>Any</strong>, if the query provider supports them.</p>
<p><pre class="brush: csharp;">
var ids = new List&lt;int&gt; { 1, 3, 5 };

var q = from c in db.Customers
        where ids.Contains(c.CustomerId)
        select c;
</pre></p>
<p>As far as FromCache was concerned, <strong>ids</strong> is just a constant expression, and treated it no differently to any other constant when evaluating its cache key.</p>
<p>Unfortunately, the ToString implementation of Lists (and of Arrays, and IEnumerables in general) is not suitable for use as a cache key, because it outputs the type name and not (for example) a representation of every element in the collection. </p>
<p>I couldn&#8217;t understand how I&#8217;d overlooked this. But then I remembered that Entity Framework v1, which was the main provider I was using at the time, <a href="http://stackoverflow.com/questions/1335732/collection-valued-parameters-with-the-entity-framework">didn&#8217;t support</a> local collections either!</p>
<div class="highlightbox">I&#8217;d actually written my own <strong>WhereAny</strong> and <strong>WhereAll</strong> methods, which build up expressions from local collections and produce queries that Entity Framework v1 could understand. But that post never made it out of my WordPress drafts. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </div>
<p>LINQ to SQL has always supported the Contains method, and Entity Framework now supports both Any and Contains overloads with local collections. So, I&#8217;ve updated the original source code and the blog post to support local collections. </p>
<p>This involves a pass over the expression tree to expand appropriate local collection values which might be used in methods like Any or Contains. Each method call in the expression tree is examined, and the <em>argument</em> to any <em>parameters of type IEnumerable&lt;&gt; or List&lt;&gt;</em> is wrapped in an object with an implementation of ToString which prints every element in the collection.</p>
<p>I&#8217;ve also extracted the method IQueryable.<strong>GetCacheKey</strong> and made it public, which could help emphasise that the meat of the idea is to  automatically generate a cache key for a query (and that you can do whatever you like with it, such as make a FromCache extension method, or managing the cache manually). </p>
<p>If you&#8217;re using the FromCache extension method, please update use the <a href="/2008/08/07/caching-the-results-of-linq-queries/">latest version</a> of the source code!</p>
<div class="highlightbox">.NET 4 methods are now included in the source for those of you using 3.5.</div>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://petemontgomery.wordpress.com/2011/01/03/fromcache-now-supports-local-collections/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f01%2f03%2ffromcache-now-supports-local-collections%2f&amp;bgcolor=33CC33" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/453/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=453&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2011/01/03/fromcache-now-supports-local-collections/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2011%2f01%2f03%2ffromcache-now-supports-local-collections%2f&#38;bgcolor=33CC33" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>Understanding IEnumerable and the iterator design pattern</title>
		<link>http://petemontgomery.wordpress.com/2010/12/08/understanding-ienumerable-iterator-pattern/</link>
		<comments>http://petemontgomery.wordpress.com/2010/12/08/understanding-ienumerable-iterator-pattern/#comments</comments>
		<pubDate>Wed, 08 Dec 2010 17:37:00 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=297</guid>
		<description><![CDATA[This is an unpolished post I used for a talk I just did at work&#8230; The generic IEnumerable interface is the most important abstraction in the .NET framework after System.Object. If you&#8217;re not 100% comfortable with IEnumerable and IEnumerable&#60;T&#62;, this introductory article might help! Prerequisites What&#8217;s an interface? An interface, in the general sense, is just [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=297&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="highlightbox">This is an unpolished post I used for a talk I just did at work&#8230;</div>
<p>The generic <strong>IEnumerable</strong> interface is the most important abstraction in the .NET framework after System.Object.</p>
<p>If you&#8217;re not 100% comfortable with IEnumerable and IEnumerable&lt;T&gt;, this introductory article might help!</p>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Prerequisites</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">What&#8217;s an interface?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">An interface, in the general sense, is just the publicly exposed signature of a type.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">##use the word &#8220;type&#8221; for class or struct.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">We can describe an interface by writing out the full public signature of a type.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">##e.g. signature of well-known class;</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">All types have &#8220;an interface&#8221; in this basic sense.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">##implementation</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">.NET interface types</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Java and .NET also support a programming construct called an interface type, defined using the interface keyword. This is a formalization of the general OO concept of &#8220;interface&#8221;.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">##e.g. definition of some interface</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">What? An interface type is just an abstract class with no implementation allowed.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Why? To allow a limited form of multiple inheritance.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">##e.g. definition of a class with inheriting base class and interfaces</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">When you &#8220;inherit&#8221; from an interface, this means that your type must implement the interface&#8217;s methods. This means your type can be used in situations that only require that your type supports a given interface. Often this functionality not directly related to the main job of the type. Interfaces give you a way of mixing and composing functionality into a type, allowing it to be used in more situations.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Common .NET interfaces</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">IComparable &#8211; an object that can be compared with other objects of the same type</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">IConvertible &#8211; an object that can be converted to different types</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">ISerializable &#8211; an object that can be serialized</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">IDisposable &#8211; an object that can deterministically clean up after itself</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">By convention, .NET interface type names are prefixed with I. Unfortunately this makes them less friendly and intuitive than normal classes. Just pretend the &#8216;I&#8217; isn&#8217;t there when you read them, and keep in mind that interface types are simply a kind of abstract class.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">So, interface types can just be used in the same way as other types. In particular, you can declare variables and parameters of interface types.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">bool IsABiggerThanB(IComparable a, IComparable b)</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">{</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">return a.CompareTo(b) &gt; 0;</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">}</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Here, parameters a and b can be of any type * that implements IComparable, which means they must define a CompareTo method.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">[* Footnote. In this case, a and b have have to be the same type as each other, or a runtime exception will be thrown by the CompareTo.]</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The CompareTo method returns 1 if the object is bigger, 0 if the same, and -1 if smaller than the object passed to it.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Many types in the .NET Framework support IComparable. For example, you can compare strings to sort them into alphabetical order.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Notice how inflexible this would be without interface types. We&#8217;d either have to</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">(1) inherit from some kind of &#8220;Comparable&#8221; class, using up our only base class, or</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">(2) support comparability in an ad-hoc, incompatible way for each type (making the polymorphic code above impossible).</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Where are we?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Interface types support rich object oriented polymorphism without the burden of full-blown multiple inheritance.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The Iterator design pattern</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Provides a way to traverse the elements of an aggregate object without exposing the underlying representation.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">[GoF, 1995]</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Aggregate object = a data structure; a collection, list or sequence of things of the same type.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Why?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">- You might need different kinds of traversal (e.g. forwards, backwards, in-order, pre-order).</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">- You might want to keep track of several traversals on the same collection at once.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">- All collections, lists, sequences etc. should be traversable in the same way.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">But what about&#8230;?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Often a list can be traversed with a basic for loop. For example, we can keep track of the current position in a list with a local integer variable and index into an array.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">for (int i = 0; i &lt; 10; i++)</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">{</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">object current = myCollection[i];</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">}</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">But this will only work if the collection is the kind of collection that can be indexed in to, such as a simple list or array. It doesn&#8217;t make any sense to &#8220;index&#8221; into a binary tree, for example; nor into many other data structures that we might want to traverse.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Could we use this method to traverse an infinite list? What if the size were unknown?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The Iterator pattern in .NET</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The Iterator design pattern takes the responsibility for traversal out of the collection itself, and puts it into another object. This specialised object is responsible only for traversing the collection (in a particular way), and nothing else.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">For example, an instance of this specialised object will probably contain a pointer to keep track of the current item, and code implementing the particular traversal logic. The class will have intimate knowledge of the collection class that it supports traversal over, and may well be defined as a nested class.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The Iterator pattern is supported in the .NET framework via two interface types in the System.Collections namespace.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">IEnumerator &#8211; a specialised object responsible for doing the traversal</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">IEnumerable &#8211; a data structure that can be traversed</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Notice how Microsoft helps matters by using &#8216;enumerate&#8217; instead of &#8216;iterate&#8217;. So you can think instead of &#8220;the Enumerator pattern&#8221; if you like. Also note that this sense of &#8216;enumerate&#8217; has nothing whatever to do with enumerated types (enums in C#).</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">public interface IEnumerator</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">{</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">object Current { get; }</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">bool    MoveNext();</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">}</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">This type is the key to the Iterator pattern. It defines the simplest possible interface for traversing a data structure. An enumerator object can tell you what the current item is, and you can tell it to move to the next item, and that&#8217;s it.(*) If MoveNext is false, we have run out of items. These two methods are just a slightly more flexible way of supporting the operation &#8220;Give me the next one&#8221;, which is the essence of the enumerator interface.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">(*) There are one or two other methods on the interface, but they&#8217;re not essential to understanding the pattern.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Notice the interface makes no assumptions at all about the structure, internal implementation or size of the data strucure that is being traversed. It&#8217;s perhaps the purest notion of a &#8220;sequence&#8221; you can think of.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">while (enumerator.MoveNext())</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">{</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">object current = enumerator.Current;</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">}</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Note that Microsoft could have designed this type as an abstract class instead of an interface type.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Great &#8211; now we can iterate over any kind of collection or sequence using this code, provided we have an enumerator for that kind of sequence.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">If only we had a standardised way to get an enumerator!</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">public interface IEnumerable</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">{</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">IEnumerator GetEnumerator();</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">}</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">This is the public face of the Iterator pattern in .NET. It simply provides a well-known way to get an instance of a default enumerator for a particular sequence or collection.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">So, if I give you an object that is enumerable, you can call GetEnumerator to give you a nice enumerator object that you can use to do a standard traversal of the object&#8217;s items.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The IEnumerable interface is implemented by many different types, including all collection types, and even the String class.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">string s = &#8220;abcdef&#8221;;</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">IEnumerator enumerator = s.GetEnumerator();</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">while (enumerator.MoveNext())</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">{</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Console.Write( ((char) enumerator.Current) + &#8220;.&#8221; );</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">}</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">// output: &#8220;a.b.c.d.e.f.&#8221;</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Language-level support</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">It turns out that this usage pattern (obtaining the default enumerator, then calling MoveNext on it in a loop) is so common it is formalised into a rather helpful language-level construct in C# and VB.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">If you&#8217;ve ever wondered how the foreach keyword works, now you know. The following code is identical to the previous example.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">string s = &#8220;abcdef&#8221;;</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">foreach (char c in s)</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">{</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Console.Write(c + &#8220;.&#8221;);</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">}</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The C# compiler simply expands this code to that in the previous example. The intermediate language produced is identical.(*)</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">(*) OK, it&#8217;s not, but assume it is. Check out the difference in Reflector.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Where are we?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">The Iterator design pattern is deeply supported in the .NET framework class library and languages.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Where next? Generics in .NET 2.0 improved support for the pattern by adding strongly-typed versions of the interfaces, IEnumerator&lt;T&gt; and IEnumerable&lt;T&gt;. IEnumerable&lt;T&gt; in particular plays a key role in the language integrated query (LINQ) features and C# 3.0 in general. Further support was provided in C# 2.0 for writing iterators with the yield keyword.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Why can&#8217;t the collection manage its own traversal?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:31px;width:1px;height:1px;">Depending on the kind of data structure, we&#8217;d probably need some kind private pointer inside the object to keep track of the current element, and some additional methods on the class itself. But you can see that this is not going to provide a solution to any of the above three requirements. This solution would allow one traversal at a time, and you would need to add additional methods to the class for each traversal algorithm you wanted to provide.</div>
<h2>Prerequisite &#8211; what&#8217;s an interface?</h2>
<p>An <strong>interface</strong>, in the general sense, is just the <strong>publicly exposed signature</strong> of a type, where &#8216;type&#8217; means class or struct in C#.</p>
<p>We can describe an interface by writing out the full public signature of a type.</p>
<p>public class Customer</p>
<p>{</p>
<p>public int Age{ get; }</p>
<p>public void MakeHappy();</p>
<p>// &#8230; more methods and properties!</p>
<p>}</p>
<p>This is not valid C#, but all types have &#8220;an interface&#8221; in this basic sense. Right click on <strong>string</strong> in your code and click <strong>Go to definition</strong> to see what I mean.</p>
<h2><span style="font-weight:normal;">.NET interface types</span></h2>
<p>Java and .NET also support a <strong>programming construct</strong> called an <em>interface type</em>, defined using the <strong>interface </strong>keyword. This is a formalization of the general OO concept of &#8220;interface&#8221;.</p>
<p><em><strong>What?</strong></em><strong> </strong>An interface type is really just an abstract class guaranteed to contain no implementation code.</p>
<p><em><strong>Why?</strong></em><strong> </strong>To allow a limited form of multiple inheritance.</p>
<p>When you &#8220;inherit&#8221; from an interface, you declare that you support the interface&#8217;s methods. This means your type can be used in situations that only require that it supports a given interface. I practice, this functionality is not directly related to the main job of the type. Interfaces give you a way of mixing and composing functionality into a type, allowing it to be used in more situations.</p>
<h2><span style="font-weight:normal;">Common .NET interfaces</span></h2>
<p><strong>IComparable</strong> &#8211; an object that can be compared with other objects of the same type</p>
<p><strong>IConvertible </strong>- an object that can be converted to different types</p>
<p><strong>ISerializable </strong>- an object that can be serialized</p>
<p><strong>IDisposable </strong>- an object that can deterministically clean up after itself</p>
<p>By convention, .NET interface type names are prefixed with I. Unfortunately this makes them less friendly and intuitive than normal classes. Just pretend the &#8216;I&#8217; isn&#8217;t there when you read them, and keep in mind that interface types are simply a special kind of abstract class.</p>
<p>So, interface types can just be used in the same way as other types. In particular, you can declare variables and parameters of interface types.</p>
<p>bool IsABiggerThanB(IComparable a, IComparable b)</p>
<p>{</p>
<p>return a.CompareTo(b) &gt; 0;</p>
<p>}</p>
<p>Here, parameters <strong>a</strong> and <strong>b</strong> can be of any type* that implements <strong>IComparable</strong>, which means they must define a <strong>CompareTo </strong>method.</p>
<p>[* Footnote. In this case, a and b have have to be the same type as each other, or a runtime exception will be thrown by CompareTo.]</p>
<p>The CompareTo method returns 1 if the object is bigger, 0 if the same, and -1 if smaller than the object passed to it. Many types in the .NET Framework support IComparable. For example, you can compare strings to sort them into alphabetical order.</p>
<p>Notice how inflexible this would be without interface types. We&#8217;d either have to</p>
<p>(1) inherit from some kind of &#8220;Comparable&#8221; class, using up our only base class, or</p>
<p>(2) support comparability in an ad-hoc, incompatible way for each type (making the polymorphic code above impossible).</p>
<h2><span style="font-weight:normal;">Where are we?</span></h2>
<p>Interface types support rich object oriented polymorphism without the burden of full-blown multiple inheritance.</p>
<h2><span style="font-weight:normal;">The Iterator design pattern</span></h2>
<p><em>Provides a way to traverse the elements of an aggregate object without exposing the underlying representation.</em></p>
<p>[GoF, 1995]</p>
<p>Aggregate object = a data structure; a collection, list or sequence of things of the same type.</p>
<h2><span style="font-weight:normal;">Why?</span></h2>
<ul>
<li>You might need different kinds of traversal (e.g. forwards, backwards, in-order, pre-order).</li>
<li>You might want to keep track of several traversals on the same collection at once.</li>
<li>All collections, lists, sequences etc. should be traversable in the same way.</li>
</ul>
<p>Sure, often a list can be traversed with a basic for loop. For example, we can keep track of the current position in a list with a local integer variable and index into an array.</p>
<p>for (int i = 0; i &lt; 10; i++)</p>
<p>{</p>
<p>object current = myCollection[i];</p>
<p>}</p>
<p>But this will only work if the collection is the kind of collection that can be indexed in to, such as a simple list or array. It doesn&#8217;t make any sense to &#8220;index&#8221; into a <strong>binary tree</strong>, for example; nor into many other data structures that we might want to traverse.</p>
<div id="attachment_299" class="wp-caption alignnone" style="width: 343px"><a href="http://petemontgomery.files.wordpress.com/2009/05/binarytree1.jpg"><img class="size-full wp-image-299 " title="A Binary Tree" src="http://petemontgomery.files.wordpress.com/2009/05/binarytree1.jpg?w=480" alt="A Binary Tree (from http://www.math.bas.bg)"   /></a><p class="wp-caption-text">A binary tree from math.bas.bg</p></div>
<p>What about <strong>infinite lists</strong>? What if the size were unknown?</p>
<h2><em><span style="font-weight:normal;">Why can&#8217;t the collection manage its own traversal?</span></em></h2>
<p>Depending on the kind of data structure, we&#8217;d probably need some kind private pointer inside the object to keep track of the current element, and some additional methods on the class itself. But you can see that this is not going to provide a solution to any of the above three requirements. This solution would allow one traversal at a time, and you would need to add additional methods to the class for each traversal algorithm you wanted to provide.</p>
<h2>The Iterator design pattern in .NET</h2>
<p>The Iterator pattern takes the responsibility for traversal <strong>out of the collection itself, and puts it into another object</strong>. This specialised object is responsible only for traversing the collection (in a particular way), and nothing else.</p>
<p>For example, an instance of this specialised object might contain a pointer to keep track of the current item, and some code implementing the particular traversal logic. The class will probably have <strong>intimate knowledge</strong> of the collection class that it supports traversal over, and might well be defined as a nested class.</p>
<p>The Iterator pattern is supported in the .NET framework v1 via two interface types in the <strong>System.Collections</strong> namespace.</p>
<p><strong>IEnumerator</strong> &#8211; a specialised object responsible for <em>doing the traversal</em></p>
<p><strong>IEnumerable </strong>- a data structure that<em> can be traversed</em></p>
<p>Microsoft uses &#8216;enumerate&#8217; instead of &#8216;iterate&#8217;. So you can think instead of &#8220;the Enumerator pattern&#8221; if you like. Also note that this sense of &#8216;enumerate&#8217; has nothing really to do with enumerated types (enums in C#).</p>
<p>public interface IEnumerator</p>
<p>{</p>
<p>object Current { get; }</p>
<p>bool    MoveNext();</p>
<p>}</p>
<p>This interface is the really the key to the pattern. It defines pretty much the <strong>simplest possible</strong> interface for traversing over a data structure. An enumerator object can tell you what the current item is, and you can tell it to move to the next item, and that&#8217;s it.(*) If MoveNext is false, we have run out of items. These two methods are just a slightly more verbose way of supporting the operation &#8220;<strong>Give me the next one</strong>&#8220;, which is the essence of the enumerator interface.</p>
<p>Notice the enumerator interface makes no assumptions at all about the structure, internal implementation or size of the data strucure that is being traversed. It&#8217;s perhaps the purest notion of a &#8220;sequence&#8221; you can think of.</p>
<p>(*) There are one or two other methods on the interface, but they&#8217;re not essential to understanding the pattern.</p>
<p>while (enumerator.MoveNext())</p>
<p>{</p>
<p>object current = enumerator.Current;</p>
<p>}</p>
<p>Note that Microsoft could have designed this type as an abstract class instead of an interface type.</p>
<p>Great &#8211; so now we can iterate over <strong>any kind</strong> of collection or sequence using this code, provided we have an enumerator for that kind of sequence.</p>
<p>If only we had a standardised way to <strong>get an enumerator</strong>!</p>
<p>public interface IEnumerable</p>
<p>{</p>
<p>IEnumerator GetEnumerator();</p>
<p>}</p>
<p>This is the public face of the Iterator pattern in .NET. It simply provides a well-known way to get an instance of a default enumerator for a particular sequence or collection.</p>
<p>So, if I give you an object that is enumerable, you can call GetEnumerator to give you a nice enumerator object that you can use to do a standard traversal of the object&#8217;s items.</p>
<p>The IEnumerable interface is implemented by many different types, including all collection types, and even the String class.</p>
<p>string s = &#8220;abcdef&#8221;;</p>
<p>IEnumerator enumerator = s.GetEnumerator();</p>
<p>while (enumerator.MoveNext())</p>
<p>{</p>
<p>Console.Write( ((char) enumerator.Current) + &#8220;.&#8221; );</p>
<p>}</p>
<p>// output: &#8220;a.b.c.d.e.f.&#8221;</p>
<h2>Language-level support</h2>
<p>It turns out that this usage pattern (obtaining the default enumerator, then calling MoveNext on it in a loop) is <strong>so common</strong> it is formalised into a helpful language-level construct in C# and VB.</p>
<p>If you&#8217;ve ever wondered how the <strong>foreach </strong>keyword works, now you know. The following code is identical to the previous example.</p>
<p>string s = &#8220;abcdef&#8221;;</p>
<p>foreach (char c in s)</p>
<p>{</p>
<p>Console.Write(c + &#8220;.&#8221;);</p>
<p>}</p>
<p>The C# compiler simply expands this code to that in the previous example. The intermediate language produced is identical.(*)</p>
<p>(*) OK, it&#8217;s not, but assume it is. Check out the difference in Reflector.</p>
<h2>Where are we?</h2>
<p>The Iterator design pattern is deeply supported in the .NET framework class library and languages.</p>
<h2>Where next?</h2>
<p>Generics in .NET 2.0 improved support for the pattern by adding strongly-typed versions of the interfaces, IEnumerator&lt;T&gt; and IEnumerable&lt;T&gt;. IEnumerable&lt;T&gt; in particular plays a key role in the language integrated query (LINQ) features and C# 3.0 in general. The C# 2.0 compiler was given the power to write its own iterator implementations via the <strong>yield </strong>keyword.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/297/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=297&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2010/12/08/understanding-ienumerable-iterator-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://petemontgomery.files.wordpress.com/2009/05/binarytree1.jpg" medium="image">
			<media:title type="html">A Binary Tree</media:title>
		</media:content>
	</item>
		<item>
		<title>A free implementation of the Microsoft XDT language</title>
		<link>http://petemontgomery.wordpress.com/2010/09/20/microsoft-xdt-language/</link>
		<comments>http://petemontgomery.wordpress.com/2010/09/20/microsoft-xdt-language/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 00:28:15 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=319</guid>
		<description><![CDATA[The XML Document Transform language, or XDT, shipped with Visual Studio 2010. It&#8217;s an XML dialect designed to help you automatically transform your .NET config files appropriately for your various deployment environments. Great. I love XML, obviously Don&#8217;t worry, XDT is very simple and specifically designed for the task of transforming configuration files. For this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=319&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dotnetkicks.com/kick/?url=http://petemontgomery.wordpress.com/2010/09/20/microsoft-xdt-language/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2010%2f09%2f20%2fmicrosoft-xdt-language%2f&amp;bgcolor=33CC33" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>The <strong>XML Document Transform</strong> language, or <strong>XDT</strong>, shipped with Visual Studio 2010. It&#8217;s an XML dialect designed to help you <strong>automatically transform</strong> your .NET config files appropriately for your various deployment environments.</p>
<h2>Great. I love XML, obviously</h2>
<p>
Don&#8217;t worry, XDT is very simple and specifically designed for the task of transforming configuration files. For this scenario, it is much easier to use than a general-purpose transformation language like XSLT.
</p>
<p>
Application configuration files tend to be <strong>mostly identical</strong> across different deployment environments. Only small modifications, such as the value of your connection strings, the debug attribute, and so on, are required to create a production Web.config file out of a development Web.config file.
</p>
<div class="highlightbox">XDT is a <strong>very simple</strong> way of expressing <strong>small differences</strong> between two XML documents.</div>
<p>
To show how simple it is, the basic semantics of the language can be expressed in a few lines of C#.
</p>
<p>
Let&#8217;s assume an existing Web.config file for our <strong>input document</strong>. We&#8217;ll also write a small XDT <strong>transform document</strong> which sets the ASP.NET debug attribute to false:
</p>
<p><pre class="brush: xml;">
&lt;configuration xmlns:xdt=&quot;http://schemas.microsoft.com/XML-Document-Transform&quot;&gt;
	&lt;system.web&gt;
		&lt;compilation debug=&quot;false&quot; xdt:Transform=&quot;SetAttributes&quot; /&gt;
	&lt;/system.web&gt;
&lt;/configuration&gt;
</pre></p>
<p>
Notice it looks a bit like a small Web.config document. The input doc could be a big, complex Web.config file, but that doesn&#8217;t matter &#8211; the transform doc only needs to contain the <strong>differences</strong>.
</p>
<p>
 The <strong>Transform</strong> attribute is defined within a distinguished XML namespace to ensure that it can&#8217;t clash with any existing attributes in the input doc. In this case, we&#8217;re using one of the most useful built-in transforms, <strong>SetAttributes</strong>, which modifies attribute values on the targeted element to those that are specified in the transform doc &#8211; in this case, setting <code>debug</code> to <code>false</code>. There are other useful transforms, such as <strong>Remove</strong> and <strong>Replace</strong>, which alter the targeted element in different ways.
</p>
<p>
A transform <strong>implicitly specifies</strong> the element(s) in the input document to act upon by virtue of the element that it belongs to: expressed in XPath, the above transform would target the<br />
<code>/configuration/system.web/compilation</code> element(s).
</p>
<div class="highlightbox">
A transform doc specifies a <strong>set of transforms</strong>, each paired with an XPath expression selecting the target element(s) in the input doc upon which to act.
</div>
<p>
Here is a simple implementation of XDT using C#:
</p>
<p><pre class="brush: csharp;">
        public XDocument Transform(XDocument inputDoc, XDocument transformDoc)
        {
            var workingDoc = new XDocument(inputDoc);

            // (1) pair each &quot;Transform&quot; element with the element(s)
            // it targets in the working document
            var xs = from e in transformDoc.Descendants()
                     from a in e.Attributes(Namespaces.Xdt + &quot;Transform&quot;)
                     let xpath = GetElementXPath(e)
                     select new
                     {
                         TransformElement = e,
                         TargetElements = workingDoc.XPathSelectElements(xpath)
                     };

            // (2) apply each transform to its target elements
            foreach (var x in xs)
            {
                ApplyTransform(x.TransformElement, x.TargetElements);
            }

            return workingDoc;
        }
</pre></p>
<h2>Show me the source code</h2>
<p>
This is a slight simplification, and of course doesn&#8217;t show you the implementation of the individual transforms or how to compute the XPath. You can find the full, reasonably <a href="http://code.google.com/p/xdt/">complete implementation of XDT</a> on Google Code.
</p>
<h2>Locators</h2>
<p>
The implicit XPath location of, for example, a <code>/configuration/appSettings/add</code> element would usually specify <strong>more than one</strong> element in most Web.config files. While this is valid, it&#8217;s not very useful. XDT provides a second attribute, <strong>Locator</strong>, which allows you to augment the implicit XPath expression with a <strong>predicate</strong> to filter the target element set:</p>
<p />
<p><pre class="brush: xml;">
                &lt;configuration xmlns:xdt=&quot;http://schemas.microsoft.com/XML-Document-Transform&quot;&gt;
                  &lt;appSettings&gt;
                    &lt;add xdt:Locator=&quot;Condition(@key='key3')&quot; /&gt;
                  &lt;/appSettings&gt;
                &lt;/configuration&gt;
</pre></p>
<p>This would give us target XPath of <code>/configuration/appSettings/add[@key='key3']</code>, which is much more useful (although it doesn&#8217;t do anything, because we haven&#8217;t specified any transform!).
</p>
<p>
A convenience case of the <strong>Condition</strong> locator is to simply <strong>Match</strong> on the specified attribute, so to actually alter a particular app setting value, you would write:</p>
<p><pre class="brush: xml;">

&lt;configuration xmlns:xdt=&quot;http://schemas.microsoft.com/XML-Document-Transform&quot;&gt;
	&lt;appSettings&gt;
		&lt;add key=&quot;key3&quot; value=&quot;new value&quot; xdt:Locator=&quot;Match(key)&quot; xdt:Transform=&quot;SetAttributes&quot; /&gt;
	&lt;/appSettings&gt;
&lt;/configuration&gt;

</pre></p>
<p>This specifies a SetAttributes transform with the same target XPath as the previous example.</p>
<h2>Why XDT?</h2>
<ul>
<li>It&#8217;s part of Visual Studio 2010, and you can expect it to become the standard way of managing different config files.</li>
<li>It&#8217;s really rather nice &#8211; it&#8217;s ideal for tweaking XML documents, so long as the changes aren&#8217;t big. It&#8217;s very readable (despite being XML) and quite easy for anyone to use.</li>
<li>You don&#8217;t really want to use XSLT for this sort of thing.</li>
</ul>
<h2>Why write a free implementation?</h2>
<p>
I wanted to use XDT in production before Visual Studio 2010 was released. I also find that thinking about the implementation of something helps you understand its semantics. However, there are some other good reasons:
</p>
<ul>
<li>XDT is currently restricted to web applications. Out of the box, it can&#8217;t be used with Windows or console apps, or even web &#8220;site&#8221; style projects. But this is no restriction of the language itself.</li>
<li>XDT is currently restricted to Web.config files. Real applications tend to have more than one XML configuration file which needs to be transformed.</li>
<li>You might not be using Visual Studio 2010.</li>
<li>You might want to decouple the notions of build <strong>configuration</strong> and build <strong>environment</strong>. They&#8217;re not the same concept, but the Visual Studio 2010 designers chose to keep things simple. With several &#8220;release&#8221; environments, this conceptual simplicity comes at the cost of flexibility and creates duplication in the project and solution manifest files. A more sophisticated build system might prefer to keep just the standard two build configurations (Debug, Release) but define several deployment environments (Dev, Test, Uat, Live&#8230;), each with different config transformations.</li>
</ul>
<div class="highlightbox">One scenario where this coupling causes a problem is building a <strong>shared code library</strong> from source inside a client application  (for example via Subversion externals). The shared library may have standard build configurations (Debug, Release), but the client applications may need additional deployment configurations, necessarily unknown to the shared library. The problem is that if these additional build configurations don&#8217;t exist in the the shared library, its projects cannot be integrated into the client solution.</div>
<p>
If you&#8217;re creating a serious build system, these restrictions would otherwise probably prevent you from using XDT for your transformations, which would be a shame.
</p>
<p>
It feels like a classic Microsoft situation &#8211; a well-engineered core technology, but  restricted (understandably) for commercial / shipping reasons. If you do want to go ahead and use this alternative implementation, it&#8217;s very straightforward to create an MSBuild task to call <strong>XdtTransformer.Transform()</strong> in order to use XDT in your build system. If there&#8217;s enough demand, I could add one to the distribution on Google Code.</p>
<div class="highlightbox"><strong>Disclaimer</strong> The semantics of this implementation are based purely on my reading of the XDT product <a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx">documentation</a> on MSDN. The implementation passes all of the example tests I&#8217;ve found on the web &#8211; but, as usual, no warranties are implied. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </div>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://petemontgomery.wordpress.com/2010/09/20/microsoft-xdt-language/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2010%2f09%2f20%2fmicrosoft-xdt-language%2f&amp;bgcolor=33CC33" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/319/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=319&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2010/09/20/microsoft-xdt-language/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2010%2f09%2f20%2fmicrosoft-xdt-language%2f&#38;bgcolor=33CC33" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2010%2f09%2f20%2fmicrosoft-xdt-language%2f&#38;bgcolor=33CC33" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>IEnumerable.GroupsOf(n)</title>
		<link>http://petemontgomery.wordpress.com/2009/04/01/ienumerable-groupsof/</link>
		<comments>http://petemontgomery.wordpress.com/2009/04/01/ienumerable-groupsof/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 10:58:13 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=259</guid>
		<description><![CDATA[A generic function to group a sequence into sequences of equal size. var numbers = new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; var groups = numbers.GroupsOf(3); Now groups is a sequence of sequences containing three items. Perhaps you might use this in some tricky UI scenario or [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=259&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A generic function to group a sequence into sequences of equal size. </p>
<p><strong>var numbers = new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };</strong></p>
<p><strong>var groups = numbers.GroupsOf(3);</strong></p>
<p>Now <strong>groups</strong> is a sequence of sequences containing three items.</p>
<div id="attachment_264" class="wp-caption alignnone" style="width: 141px"><a href="http://petemontgomery.files.wordpress.com/2009/03/groupsof3.gif"><img class="size-full wp-image-264 " title="groupsof3" src="http://petemontgomery.files.wordpress.com/2009/03/groupsof3.gif?w=480" alt="Groups of 3"   /></a><p class="wp-caption-text"> </p></div>
<p>Perhaps you might use this in some tricky UI scenario or to gamble away your integers. You&#8217;ll need the <a href="http://petemontgomery.wordpress.com/2009/03/31/ienumerator-next-count/">IEnumerator.Next</a> extension too.</p>
<p>Is this a special case of a more general function, I wonder?</p>
<div class="smallsource">
<pre class="brush: csharp;">
/// &lt;summary&gt;
/// Groups a sequence into sequences of the specified size.
/// The final group may be shorter if there are leftover
/// elements.
/// &lt;/summary&gt;
/// &lt;param name=&quot;count&quot;&gt;The size of the groups.&lt;/param&gt;
public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; GroupsOf&lt;T&gt;(
    this IEnumerable&lt;T&gt; source,
    int count)
{
    using (var it = source.GetEnumerator())
    {
        while (true)
        {
            var group = it.Next(count).ToList();

            if (group.Any())
                yield return group;
            else
                break;
        }
    }
}
</pre>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/259/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=259&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2009/04/01/ienumerable-groupsof/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://petemontgomery.files.wordpress.com/2009/03/groupsof3.gif" medium="image">
			<media:title type="html">groupsof3</media:title>
		</media:content>
	</item>
		<item>
		<title>IEnumerator.Next(count)</title>
		<link>http://petemontgomery.wordpress.com/2009/03/31/ienumerator-next-count/</link>
		<comments>http://petemontgomery.wordpress.com/2009/03/31/ienumerator-next-count/#comments</comments>
		<pubDate>Tue, 31 Mar 2009 09:58:00 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=227</guid>
		<description><![CDATA[I still find it remarkable how syntax alone can alter the way I conceptualise a problem. Here&#8217;s a useful helper for pulling the next n elements out of an enumerator. Think of it as a generalisation of MoveNext. I&#8217;ve found it handy for implementing certain IEnumerable extensions.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=227&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I still find it remarkable how syntax alone can alter the way I conceptualise a problem.</p>
<p>Here&#8217;s a useful helper for pulling the next <em>n</em> elements out of an enumerator. Think of it as a generalisation of <strong>MoveNext</strong>. I&#8217;ve found it <a href="http://petemontgomery.wordpress.com/2009/04/01/ienumerable-groupsof/">handy</a> for implementing certain IEnumerable extensions.</p>
<div class="smallsource"><pre class="brush: csharp;">
public static class EnumeratorExtensions
{
    /// &lt;summary&gt;
    /// Returns a specified number of contiguous elements
    /// from the enumerator.
    /// &lt;/summary&gt;
    public static IEnumerable&lt;T&gt; Next&lt;T&gt;(
        this IEnumerator&lt;T&gt; source,
        int count)
    {
        int counter = 0;

        while (counter &lt; count)
        {
            if (source.MoveNext())
                yield return source.Current;
            else
                break;

            counter++;
        }
    }
}
</pre></p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/227/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/227/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/227/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/227/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/227/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/227/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/227/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=227&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2009/03/31/ienumerator-next-count/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>
	</item>
		<item>
		<title>The IEnumerable.Pairwise function in C#</title>
		<link>http://petemontgomery.wordpress.com/2009/03/30/the-ienumerable-pairwise-function-in-c/</link>
		<comments>http://petemontgomery.wordpress.com/2009/03/30/the-ienumerable-pairwise-function-in-c/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 17:00:02 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[iterators]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=198</guid>
		<description><![CDATA[One handy function in the F# Seq module is Seq.pairwise. [ 1 ; 2 ; 3 ; 4 ; 5] &#124;&#62; Seq.pairwise It produces a sequence of, well, pairs: val it : seq&#60;int * int&#62; = seq [(1, 2); (2, 3); (3, 4); (4, 5)] Its main use is comparing each value in a sequence with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=198&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2009%2f03%2f30%2fthe-ienumerable-pairwise-function-in-c%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2009%2f03%2f30%2fthe-ienumerable-pairwise-function-in-c%2f&amp;bgcolor=33CC33" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>One handy function in the F# <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Collections.Seq.html">Seq</a> module is <strong>Seq.pairwise</strong>.</p>
<p><strong><strong>[</strong></strong><strong> 1 ; 2 ; 3 ; 4 ; 5] |&gt; Seq.pairwise</strong></p>
<p>It produces a sequence of, well, pairs:</p>
<p><strong><strong>v</strong></strong><strong>al it : seq&lt;int * int&gt; = seq [(1, 2); (2, 3); (3, 4); (4, 5)]</strong></p>
<p>Its main use is <strong>comparing each va</strong><strong>lue in a sequence with its successor</strong>. One example might be <a href="http://blog.magenic.com/blogs/aarone/archive/2008/12/11/One-step-closer-to-F_2300_-for-Business-Intelligence.aspx">analysing a web server log</a> for suspicious crawlers.</p>
<p>Obviously you&#8217;ll need your own <strong>Pair</strong> class, which I&#8217;ll leave to you, reader (at least until we get <a href="http://blogs.msdn.com/bclteam/archive/2008/11/04/what-s-new-in-the-bcl-in-net-4-0-justin-van-patten.aspx">tuples</a> in .NET 4). No argument checking, but otherwise I think complete. Enjoy!</p>
<p><pre class="brush: csharp;">

public static class EnumerableExtensions
{
    /// &lt;summary&gt;
    /// Returns a sequence of each element in the input sequence and its
    /// predecessor, with the exception of the first element which is only
    /// returned as the predecessor of the second element.
    /// &lt;/summary&gt;
    public static IEnumerable&lt;Pair&lt;T, T&gt;&gt; Pairwise&lt;T&gt;(
        this IEnumerable&lt;T&gt; source)
    {
        T previous = default(T);

        using (var it = source.GetEnumerator())
        {
            // skip the first element
            if (it.MoveNext())
                previous = it.Current;

            while (it.MoveNext())
            {
                yield return new Pair&lt;T, T&gt;
                {
                    First  = previous,
                    Second = it.Current
                };

                previous = it.Current;
            }
        }
    }
}
</pre></p>
<div class="highlightbox"><strong>Update</strong> .NET 4 introduced the <strong>Enumerable.Zip</strong> method into the framework which can be used to easily create a pairwise sequence in C#. </p>
<p> ts.Zip(us.Skip(1), (t, u) =&gt; new { t, u}); </p></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/198/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=198&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2009/03/30/the-ienumerable-pairwise-function-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2009%2f03%2f30%2fthe-ienumerable-pairwise-function-in-c%2f&#38;bgcolor=33CC33" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>Query string extension methods for System.UriBuilder</title>
		<link>http://petemontgomery.wordpress.com/2009/01/27/query-string-extension-methods-for-systemuribuilder/</link>
		<comments>http://petemontgomery.wordpress.com/2009/01/27/query-string-extension-methods-for-systemuribuilder/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 13:15:42 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Extension Methods]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=87</guid>
		<description><![CDATA[The System.UriBuilder class gives you additional security and correctness over manipulating URL strings, but inexplicably lacks support for manipulating query strings. A convenient API can be grafted with a couple of extension methods, GetQueryParams() and SetQueryParam(...).<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=87&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2009%2f01%2f27%2fquery-string-extension-methods-for-systemuribuilder%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2009%2f01%2f27%2fquery-string-extension-methods-for-systemuribuilder%2f&amp;bgcolor=33CC33" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>In contrast with its more famous sibling <strong>System.StringBuilder</strong>, the <strong>System.UriBuilder</strong> class goes mostly unnoticed and unloved.</p>
<p>This is unfortunate, since although the URI is just a string, it&#8217;s restricted by detailed <a href="http://www.ietf.org/rfc/rfc2396.txt">specification</a> to a limited subset of all possible strings. This is why we have framework and library code to help us out. Think how many bugs and security errors have been caused by concatenating general-purpose strings!</p>
<p>The .NET <strong>UriBuilder </strong>class provides additional safety but inexplicably lacks support for one of the most common reasons for concatenating strings to form a URL &#8211; manipulating query strings.</p>
<p>In particular, you often find that you would like to <em>set</em> a query key/value pair on an existing URL. You want to add it if it doesn&#8217;t already exist (but change it if it does) and leave the rest of the URL intact.</p>
<p>A convenient API can be grafted with a couple of extension methods, <strong>GetQueryParams</strong> and <strong>SetQueryParam</strong>.</p>
<p><pre class="brush: csharp;">
var uri = new UriBuilder(&quot;http://blah.com&quot;);

Assert.True( uri.GetQueryParams().Count() == 0 );
</pre></p>
<p><pre class="brush: csharp;">
uri.SetQueryParam(&quot;sortBy&quot;, &quot;price&quot;);

Assert.True( uri.GetQueryParams().Count() == 1 );
Assert.True( uri.Query.EndsWith(&quot;?sortBy=price&quot;) );
</pre></p>
<p><pre class="brush: csharp;">
uri.SetQueryParam(&quot;page&quot;, &quot;3&quot;);

Assert.True( uri.GetQueryParams().Count() == 2 );
Assert.True( uri.Query.Contains(&quot;page=3&quot;) );
</pre></p>
<p><pre class="brush: csharp;">
uri.SetQueryParam(&quot;page&quot;, &quot;4&quot;);

Assert.True( uri.GetQueryParams().Count() == 2 );
Assert.True( uri.Query.Contains(&quot;page=4&quot;) );
</pre></p>
<p>Here&#8217;s the full source.</p>
<p><pre class="brush: csharp;">

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections.Specialized;

// ...

    public static class UriBuilderExtensions
    {
        /// &lt;summary&gt;
        /// Sets the specified query parameter key-value pair of the URI.
        /// If the key already exists, the value is overwritten.
        /// &lt;/summary&gt;
        public static UriBuilder SetQueryParam(this UriBuilder uri, string key, string value)
        {
            var collection = uri.ParseQuery();

            // add (or replace existing) key-value pair
            collection.Set(key, value);

            string query = collection
                .AsKeyValuePairs()
                .ToConcatenatedString(pair =&gt;
                    pair.Key == null
                    ? pair.Value
                    : pair.Key + &quot;=&quot; + pair.Value, &quot;&amp;&quot;);

            uri.Query = query;

            return uri;
        }

        /// &lt;summary&gt;
        /// Gets the query string key-value pairs of the URI.
        /// Note that the one of the keys may be null (&quot;?123&quot;) and
        /// that one of the keys may be an empty string (&quot;?=123&quot;).
        /// &lt;/summary&gt;
        public static IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; GetQueryParams(
            this UriBuilder uri)
        {
            return uri.ParseQuery().AsKeyValuePairs();
        }

        /// &lt;summary&gt;
        /// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence.
        /// &lt;/summary&gt;
        static IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; AsKeyValuePairs(this NameValueCollection collection)
        {
            foreach (string key in collection.AllKeys)
            {
                yield return new KeyValuePair&lt;string, string&gt;(key, collection.Get(key));
            }
        }

        /// &lt;summary&gt;
        /// Parses the query string of the URI into a NameValueCollection.
        /// &lt;/summary&gt;
        static NameValueCollection ParseQuery(this UriBuilder uri)
        {
            return HttpUtility.ParseQueryString(uri.Query);
        }
    }

</pre></p>
<p>The general-purpose folding function <strong>ToConcatenatedString </strong>is used in the implementation. Here it is:</p>
<p><pre class="brush: csharp;">

	public static class EnumerableExtensions
	{
		/// &lt;summary&gt;
		/// Creates a string from the sequence by concatenating the result
		/// of the specified string selector function for each element.
		/// &lt;/summary&gt;
		public static string ToConcatenatedString&lt;T&gt;(this IEnumerable&lt;T&gt; source,
			Func&lt;T, string&gt; stringSelector)
		{
			return source.ToConcatenatedString(stringSelector, String.Empty);
		}

		/// &lt;summary&gt;
		/// Creates a string from the sequence by concatenating the result
		/// of the specified string selector function for each element.
		/// &lt;/summary&gt;
		///&lt;param name=&quot;separator&quot;&gt;The string which separates each concatenated item.&lt;/param&gt;
		public static string ToConcatenatedString&lt;T&gt;(this IEnumerable&lt;T&gt; source,
			Func&lt;T, string&gt; stringSelector,
			string separator)
		{
			var b = new StringBuilder();
			bool needsSeparator = false; // don't use for first item

			foreach (var item in source)
			{
				if (needsSeparator)
					b.Append(separator);

				b.Append(stringSelector(item));
				needsSeparator = true;
			}

			return b.ToString();
		}
	}

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/87/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=87&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2009/01/27/query-string-extension-methods-for-systemuribuilder/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2009%2f01%2f27%2fquery-string-extension-methods-for-systemuribuilder%2f&#38;bgcolor=33CC33" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>Caching the results of LINQ queries</title>
		<link>http://petemontgomery.wordpress.com/2008/08/07/caching-the-results-of-linq-queries/</link>
		<comments>http://petemontgomery.wordpress.com/2008/08/07/caching-the-results-of-linq-queries/#comments</comments>
		<pubDate>Thu, 07 Aug 2008 12:23:54 +0000</pubDate>
		<dc:creator>Pete Montgomery</dc:creator>
				<category><![CDATA[Building a Domain Query Layer in .NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://petemontgomery.wordpress.com/?p=5</guid>
		<description><![CDATA[An essential feature of many applications is a caching architecture. What if your query layer could offer an easy way to optionally cache the result of any query issued against it? Ideally, this would work for any LINQ query (over objects, XML, SQL, Entities&#8230;) work for anonymous type projections, as well as business entities be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=5&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>An essential feature of many applications is a <strong>caching architecture</strong>. What if your query layer could offer an easy way to <strong>optionally cache</strong> the result of any query issued against it? Ideally, this would</p>
<ul>
<li>work for <strong>any</strong> LINQ query (over objects, XML, SQL, Entities&#8230;)</li>
<li>work for <strong>anonymous type</strong> projections, as well as business entities</li>
<li>be statically <strong>type safe</strong> (no casting required)</li>
<li>deal transparently with <strong>cache key</strong> creation</li>
<li>look <strong>syntactically</strong> like a custom query operator</li>
</ul>
<div class="smallsource"><pre class="brush: css;">
var q = from c in context.Customers
        where c.City == &quot;London&quot;
        select new { c.Name, c.Phone };

var result = q.Take(10).FromCache();
</pre></p>
</div>
<p>The <strong>FromCache</strong> extension method offers a nice way to opt in for <strong>local result caching on any LINQ query</strong>. Here&#8217;s the method signature:</p>
<p><pre class="brush: csharp;">
/// &lt;summary&gt;
/// Returns the result of the query; if possible from the cache, otherwise
/// the query is materialized and the result cached before being returned.
/// &lt;/summary&gt;
public static IEnumerable&lt;T&gt; FromCache&lt;T&gt;(this IQueryable&lt;T&gt; query) { ... }
</pre></p>
<p>Note that this works for any <strong>IQueryable&lt;T&gt;</strong>, and for any <strong>T</strong> (including anonymous types). The complete source is available at the bottom of the article. There&#8217;s an additional overload to allow more sophisticated caching policies to be specified, and of course you could easily add more.</p>
<h2>Formulating the cache key</h2>
<p>The main challenge is to <strong>automatically generate a cache key</strong> which is sufficiently unique for the query, using only the query and no additional user-supplied information. Normally, cache key generation logic tends to permeate application code and really clutter it up. Handliy, LINQ queries are self-describing &#8211; what &#8220;identifies&#8221; a query is the <strong>expression </strong>it represents, and this is completely captured by the query&#8217;s expression tree.</p>
<p>Clearly it is possible to <strong>generate a textual representation</strong> of an expression tree &#8211; that&#8217;s almost exactly what they were designed for, and exactly how LINQ to SQL works. All we need to do is build a query evaluater which, instead of generating SQL, returns a suitable textual representation of the query.</p>
<p>Luckily the <strong>ToString</strong> method on the Expression class already does almost exactly this. Look what it produces for this simple predicate expression:</p>
<p><pre class="brush: css;">
Expression&lt;Func&lt;Customer, bool&gt;&gt; predicate = c =&gt; c.Name.StartsWith(&quot;Smith&quot;);

Console.WriteLine(predicate.ToString());
</pre></p>
<p><pre class="brush: css;">
&quot;c =&gt; c.Name.StartsWith(\&quot;Smith\&quot;)&quot;
</pre></p>
<p>The information contained in the expression tree data structure allows the Expression.ToString implementation to produce a string representation which <strong>looks something like the query&#8217;s source code</strong>. This is a great candidate for our cache key!</p>
<h2>Partial evaluation</h2>
<p>A subtle problem is that the ToString output won&#8217;t be unique enough if the expression contains &#8220;local&#8221; nodes which haven&#8217;t been evaluated yet. In particular, the way the C# and VB compilers <a href="http://blogs.msdn.com/b/oldnewthing/archive/2006/08/02/686456.aspx">implement closures</a> means that local variable values you might expect to be present in the query are actually on the other end of closure references.</p>
<p><pre class="brush: css;">
string pattern = &quot;Smith&quot;;
predicate = c =&gt; c.Name.StartsWith(pattern);

Console.WriteLine(predicate.ToString());
</pre></p>
<p><pre class="brush: css;">
&quot;c =&gt; c.Name.StartsWith(value(App.Program+&lt;&gt;c__DisplayClass1).pattern)&quot;
</pre></p>
<p>Unfortunately, exactly the same string representation would be also produced by a query for &#8220;Jones&#8221;. This is because the expression now contains a reference to an unevaluated member of a captured variable. This is what Matt Warren calls the <a href="http://blogs.msdn.com/mattwar/archive/2007/06/01/iqueryable-s-deep-dark-secret.aspx">closure mess</a>.</p>
<p>Recall that LINQ queries are not evaluated until the last possible opportunity. If we were to build a query provider, we would need to evaluate all such unevaluated local expressions <strong>just before</strong> we generated our SQL (or whatever). If only we had a function like so:</p>
<p><pre class="brush: css;">
predicate = Evaluator.PartialEval(predicate)
</pre></p>
<p>Such a sample implementation of partial query evaluation is provided by Microsoft in <a href="http://msdn.microsoft.com/en-us/library/bb546158.aspx">Creating an IQueryable LINQ Provider</a>. Applying the <strong>PartialEval</strong> function to the expression walks the tree, evaluates locally-evaluable nodes and returns the simplified expression. This neatly gets us back to our original ToString expression representation.</p>
<p><pre class="brush: css;">
&quot;c =&gt; c.Name.StartsWith(\&quot;Smith\&quot;)&quot;
</pre></p>
<p>An additional complexity is this: For ConstantExpressions, the ToString implementation simply delegates to the underlying wrapped object. We therefore need to be careful about what we allow to be wrapped in a ConstantExpression during partial evaluation. For example, the string representation of a LINQ to SQL IQueryable object is some version of the SQL that it would like to generate. This may not be enough to ensure uniqueness. Therefore we need to supply a slightly more sophisticated rule to PartialEval which determines whether a given node in the query is locally evaluable in order to prevent <strong>raw queries</strong> being locally evaluated and wrapped in ConstantExpressions by the partial evaluator.</p>
<div class="highlightbox">This issue caused a few bug reports when I first released the source code, in particular for TVF functions in LINQ to SQL.</div>
<h2>Local collections</h2>
<p>Local collection values can be supplied as parameters to query operators such as <strong>Contains</strong> and <strong>Any</strong>, if the query provider supports them.</p>
<p>LINQ to SQL and now Entity Framework v4 both support local collection values. However, local collections (such as lists or arrays) are just constant expressions in a query, so special support is needed to ensure that a suitable cache key is created representing each of their elements.</p>
<p>This is implemented by a pass over the expression tree to make appropriate local collection values expand themselves during ToString invocation. Each method call in the expression is examined, and the argument to any parameters of type IEnumerable&lt;&gt; or List&lt;&gt; is wrapped in an object with an implementation of ToString which prints every element in the collection.</p>
<div class="highlightbox">Please see <a href="/2011/01/03/fromcache-now-supports-local-collections/">this post</a> for more info on LocalCollectionExpander.</div>
<h2>Squashing the key</h2>
<p>A final problem is that the cache key string could get very big, especially for complicated queries. Unless your query results are really super-sensitive, it&#8217;s fine to use an MD5 fingerprint of the key instead. MD5 fingerprints are not <em>guaranteed</em> to be be unique, but it should be <a href="http://www.ietf.org/rfc/rfc1321.txt">computationally infeasible</a> to find two identical fingerprints.</p>
<h2>Gotchas</h2>
<h3>(1) Multiple data sources of the same type</h3>
<p>While generating a cache key from the query expression in this manner is pretty elegant and very useful for LINQ-based applications and libraries, you should take care when using more than one query datasource of the same data type.</p>
<p>Constants in the query (including IQueryables) create the same key. Two different sources of type IQueryable&lt;Customer&gt; are <strong>not distinguished from each other</strong> &#8211; the same queries against them will generate identical cache keys. Usually this is <strong>what you want</strong> &#8211; for example, you want to be able to cache the results of a query regardless of which data context <em>instance</em> the query was issued against.</p>
<p>It (theoretically) may not be what you want in some scenarios. If in doubt, double-check that the cache key strings being generated don&#8217;t conflict.</p>
<h3>(2) Caching and object-relational mapping</h3>
<p>ORMs generally have their own internal object manager. You will need to make sure that your query results from any such provider (LINQ to SQL, Entity Framework, etc.) are released from their object manager.</p>
<div>
<ul>
<li>For LINQ-to-SQL, set <strong>ObjectTrackingEnabled = false</strong> on your DataContext.</li>
<li>For Entity Framework, this can be enforced in the FromCache method itself.</li>
<li>For this, and other data sources, see the todo: in the source code.</li>
</ul>
<h3>(3) It&#8217;s a cache</h3>
<p>Remember that the normal consequences of caching still apply. Any object reference put into an application-wide cache will be kept alive indeterminately. Once you put something into cache it can (and probably will) be accessed from arbitrary threads. Cached objects should probably be treated as read-only data.</p>
</div>
<h2>Cache provider</h2>
<p>This example implementation of FromCache uses the <strong>System.Web.Caching.Cache</strong> class. It&#8217;s worth noting that this useful class isn&#8217;t really specific to ASP.NET, and can be used by any .NET application or library. You&#8217;ll just need a reference to the System.Web assembly. (Note that its use outside web applications is <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx">not officially supported</a> by Microsoft.)</p>
<p>Alternatively, you could just as easily use this technique with another cache implementation.</p>
<div class="highlightbox">In a recent update to the source code I have extracted the public method IQueryable.<strong>GetCacheKey</strong> which could help emphasise that the meat of the idea is to automatically generate a cache key for a query. You can do whatever you like with the key, such as make a simple FromCache extension method with the ASP.NET cache, or doing something more complicated.</div>
<h2>Source code</h2>
<p><pre class="brush: csharp;">
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Monty.Linq
{
    /// &lt;remarks&gt;
    /// Copyright (c) 2010 Pete Montgomery.
    /// http://petemontgomery.wordpress.com
    /// Licenced under GNU LGPL v3.
    /// http://www.gnu.org/licenses/lgpl.html
    /// &lt;/remarks&gt;
    public static class QueryResultCache
    {
        /// &lt;summary&gt;
        /// Returns the result of the query; if possible from the cache, otherwise
        /// the query is materialized and the result cached before being returned.
        /// The cache entry has a one minute sliding expiration with normal priority.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;T&gt; FromCache&lt;T&gt;(this IQueryable&lt;T&gt; query)
        {
            return query.FromCache(CacheItemPriority.Normal, TimeSpan.FromMinutes(1));
        }

        /// &lt;summary&gt;
        /// Returns the result of the query; if possible from the cache, otherwise
        /// the query is materialized and the result cached before being returned.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;T&gt; FromCache&lt;T&gt;(this IQueryable&lt;T&gt; query,
            CacheItemPriority priority,
            TimeSpan slidingExpiration)
        {
            string key = query.GetCacheKey();

            // try to get the query result from the cache
            var result = HttpRuntime.Cache.Get(key) as List&lt;T&gt;;

            if (result == null)
            {
                // todo: ... ensure that the query results do not
                // hold on to resources for your particular data source
                //
                //////// for entity framework queries, set to NoTracking
                //////var entityQuery = query as ObjectQuery&lt;T&gt;;
                //////if (entityQuery != null)
                //////{
                //////    entityQuery.MergeOption = MergeOption.NoTracking;
                //////}

                // materialize the query
                result = query.ToList();

                HttpRuntime.Cache.Insert(
                    key,
                    result,
                    null, // no cache dependency
                    Cache.NoAbsoluteExpiration,
                    slidingExpiration,
                    priority,
                    null); // no removal notification
            }

            return result;
        }

        /// &lt;summary&gt;
        /// Gets a cache key for a query.
        /// &lt;/summary&gt;
        public static string GetCacheKey(this IQueryable query)
        {
            var expression = query.Expression;

            // locally evaluate as much of the query as possible
            expression = Evaluator.PartialEval(expression, QueryResultCache.CanBeEvaluatedLocally);

            // support local collections
            expression = LocalCollectionExpander.Rewrite(expression);

            // use the string representation of the expression for the cache key
            string key = expression.ToString();

            // the key is potentially very long, so use an md5 fingerprint
            // (fine if the query result data isn't critically sensitive)
            key = key.ToMd5Fingerprint();

            return key;
        }

        static Func&lt;Expression, bool&gt; CanBeEvaluatedLocally
        {
            get
            {
                return expression =&gt;
                {
                    // don't evaluate parameters
                    if (expression.NodeType == ExpressionType.Parameter)
                        return false;

                    // can't evaluate queries
                    if (typeof(IQueryable).IsAssignableFrom(expression.Type))
                        return false;

                    return true;
                };
            }
        }
    }

    /// &lt;summary&gt;
    /// Enables the partial evaluation of queries.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// From http://msdn.microsoft.com/en-us/library/bb546158.aspx
    /// Copyright notice http://msdn.microsoft.com/en-gb/cc300389.aspx#O
    /// &lt;/remarks&gt;
    public static class Evaluator
    {
        /// &lt;summary&gt;
        /// Performs evaluation &amp; replacement of independent sub-trees
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;expression&quot;&gt;The root of the expression tree.&lt;/param&gt;
        /// &lt;param name=&quot;fnCanBeEvaluated&quot;&gt;A function that decides whether a given expression node can be part of the local function.&lt;/param&gt;
        /// &lt;returns&gt;A new tree with sub-trees evaluated and replaced.&lt;/returns&gt;
        public static Expression PartialEval(Expression expression, Func&lt;Expression, bool&gt; fnCanBeEvaluated)
        {
            return new SubtreeEvaluator(new Nominator(fnCanBeEvaluated).Nominate(expression)).Eval(expression);
        }

        /// &lt;summary&gt;
        /// Performs evaluation &amp; replacement of independent sub-trees
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;expression&quot;&gt;The root of the expression tree.&lt;/param&gt;
        /// &lt;returns&gt;A new tree with sub-trees evaluated and replaced.&lt;/returns&gt;
        public static Expression PartialEval(Expression expression)
        {
            return PartialEval(expression, Evaluator.CanBeEvaluatedLocally);
        }

        private static bool CanBeEvaluatedLocally(Expression expression)
        {
            return expression.NodeType != ExpressionType.Parameter;
        }

        /// &lt;summary&gt;
        /// Evaluates &amp; replaces sub-trees when first candidate is reached (top-down)
        /// &lt;/summary&gt;
        class SubtreeEvaluator : ExpressionVisitor
        {
            HashSet&lt;Expression&gt; candidates;

            internal SubtreeEvaluator(HashSet&lt;Expression&gt; candidates)
            {
                this.candidates = candidates;
            }

            internal Expression Eval(Expression exp)
            {
                return this.Visit(exp);
            }

            public override Expression Visit(Expression exp)
            {
                if (exp == null)
                {
                    return null;
                }
                if (this.candidates.Contains(exp))
                {
                    return this.Evaluate(exp);
                }
                return base.Visit(exp);
            }

            private Expression Evaluate(Expression e)
            {
                if (e.NodeType == ExpressionType.Constant)
                {
                    return e;
                }
                LambdaExpression lambda = Expression.Lambda(e);
                Delegate fn = lambda.Compile();
                return Expression.Constant(fn.DynamicInvoke(null), e.Type);
            }

        }

        /// &lt;summary&gt;
        /// Performs bottom-up analysis to determine which nodes can possibly
        /// be part of an evaluated sub-tree.
        /// &lt;/summary&gt;
        class Nominator : ExpressionVisitor
        {
            Func&lt;Expression, bool&gt; fnCanBeEvaluated;
            HashSet&lt;Expression&gt; candidates;
            bool cannotBeEvaluated;

            internal Nominator(Func&lt;Expression, bool&gt; fnCanBeEvaluated)
            {
                this.fnCanBeEvaluated = fnCanBeEvaluated;
            }

            internal HashSet&lt;Expression&gt; Nominate(Expression expression)
            {
                this.candidates = new HashSet&lt;Expression&gt;();
                this.Visit(expression);
                return this.candidates;
            }

            public override Expression Visit(Expression expression)
            {
                if (expression != null)
                {
                    bool saveCannotBeEvaluated = this.cannotBeEvaluated;
                    this.cannotBeEvaluated = false;
                    base.Visit(expression);
                    if (!this.cannotBeEvaluated)
                    {
                        if (this.fnCanBeEvaluated(expression))
                        {
                            this.candidates.Add(expression);
                        }
                        else
                        {
                            this.cannotBeEvaluated = true;
                        }
                    }
                    this.cannotBeEvaluated |= saveCannotBeEvaluated;
                }
                return expression;
            }
        }
    }

    /// &lt;summary&gt;
    /// Enables cache key support for local collection values.
    /// &lt;/summary&gt;
    public class LocalCollectionExpander : ExpressionVisitor
    {
        public static Expression Rewrite(Expression expression)
        {
            return new LocalCollectionExpander().Visit(expression);
        }

        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            // pair the method's parameter types with its arguments
            var map = node.Method.GetParameters()
                .Zip(node.Arguments, (p, a) =&gt; new { Param = p.ParameterType, Arg = a })
                .ToLinkedList();

            // deal with instance methods
            var instanceType = node.Object == null ? null : node.Object.Type;
            map.AddFirst(new { Param = instanceType, Arg = node.Object });

            // for any local collection parameters in the method, make a
            // replacement argument which will print its elements
            var replacements = (from x in map
                                where x.Param != null &amp;&amp; x.Param.IsGenericType
                                let g = x.Param.GetGenericTypeDefinition()
                                where g == typeof(IEnumerable&lt;&gt;) || g == typeof(List&lt;&gt;)
                                where x.Arg.NodeType == ExpressionType.Constant
                                let elementType = x.Param.GetGenericArguments().Single()
                                let printer = MakePrinter((ConstantExpression) x.Arg, elementType)
                                select new { x.Arg, Replacement = printer }).ToList();

            if (replacements.Any())
            {
                var args = map.Select(x =&gt; (from r in replacements
                                            where r.Arg == x.Arg
                                            select r.Replacement).SingleOrDefault() ?? x.Arg).ToList();

                node = node.Update(args.First(), args.Skip(1));
            }

            return base.VisitMethodCall(node);
        }

        ConstantExpression MakePrinter(ConstantExpression enumerable, Type elementType)
        {
            var value = (IEnumerable) enumerable.Value;
            var printerType = typeof(Printer&lt;&gt;).MakeGenericType(elementType);
            var printer = Activator.CreateInstance(printerType, value);

            return Expression.Constant(printer);
        }

        /// &lt;summary&gt;
        /// Overrides ToString to print each element of a collection.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// Inherits List in order to support List.Contains instance method as well
        /// as standard Enumerable.Contains/Any extension methods.
        /// &lt;/remarks&gt;
        class Printer&lt;T&gt; : List&lt;T&gt;
        {
            public Printer(IEnumerable collection)
            {
                this.AddRange(collection.Cast&lt;T&gt;());
            }

            public override string ToString()
            {
                return &quot;{&quot; + this.ToConcatenatedString(t =&gt; t.ToString(), &quot;|&quot;) + &quot;}&quot;;
            }
        }
    }

    public static class Utility
    {
        /// &lt;summary&gt;
        /// Creates an MD5 fingerprint of the string.
        /// &lt;/summary&gt;
        public static string ToMd5Fingerprint(this string s)
        {
            var bytes = Encoding.Unicode.GetBytes(s.ToCharArray());
            var hash = new MD5CryptoServiceProvider().ComputeHash(bytes);

            // concat the hash bytes into one long string
            return hash.Aggregate(new StringBuilder(32),
                (sb, b) =&gt; sb.Append(b.ToString(&quot;X2&quot;)))
                .ToString();
        }

        public static string ToConcatenatedString&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, string&gt; selector, string separator)
        {
            var b = new StringBuilder();
            bool needSeparator = false;

            foreach (var item in source)
            {
                if (needSeparator)
                    b.Append(separator);

                b.Append(selector(item));
                needSeparator = true;
            }

            return b.ToString();
        }

        public static LinkedList&lt;T&gt; ToLinkedList&lt;T&gt;(this IEnumerable&lt;T&gt; source)
        {
            return new LinkedList&lt;T&gt;(source);
        }
    }
}
</pre></p>
<p>The source code now assumes .NET 4 and above. If you need to run on .NET 3.5, you can use the MSDN <a href="http://msdn.microsoft.com/en-us/library/bb882521(v=vs.90).aspx">ExpressionVisitor</a> and the framework methods below.</p>
<p><pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// These methods are built-in to .NET 4 and above.
    /// &lt;/summary&gt;
    public static class Framework35Utility
    {
        public static IEnumerable&lt;R&gt; Zip&lt;T, U, R&gt;(
            this IEnumerable&lt;T&gt; first, 
            IEnumerable&lt;U&gt; second, 
            Func&lt;T, U, R&gt; selector)
        {
            using (var e1 = first.GetEnumerator())
            using (var e2 = second.GetEnumerator())
            {
                while (e1.MoveNext() &amp;&amp; e2.MoveNext())
                    yield return selector(e1.Current, e2.Current);                
            }
        }
        
        public static MethodCallExpression Update(
            this MethodCallExpression source,
            Expression @object,
            IEnumerable&lt;Expression&gt; arguments)
        {
            if (@object == source.Object &amp;&amp; arguments.SequenceEqual(source.Arguments))
            {
                return source;
            }

            return Expression.Call(@object, source.Method, arguments);
        }
    }

</pre></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2008%2f08%2f07%2fcaching-the-results-of-linq-queries%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2008%2f08%2f07%2fcaching-the-results-of-linq-queries%2f&amp;bgcolor=33CC33" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/petemontgomery.wordpress.com/5/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/petemontgomery.wordpress.com/5/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petemontgomery.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petemontgomery.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petemontgomery.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petemontgomery.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petemontgomery.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petemontgomery.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petemontgomery.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petemontgomery.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petemontgomery.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petemontgomery.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petemontgomery.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petemontgomery.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petemontgomery.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petemontgomery.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petemontgomery.wordpress.com&amp;blog=3449380&amp;post=5&amp;subd=petemontgomery&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petemontgomery.wordpress.com/2008/08/07/caching-the-results-of-linq-queries/feed/</wfw:commentRss>
		<slash:comments>62</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/76f660aeca0430d7e796f1df996e877c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Pete</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpetemontgomery.wordpress.com%2f2008%2f08%2f07%2fcaching-the-results-of-linq-queries%2f&#38;bgcolor=33CC33" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
	</channel>
</rss>
