<?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/"
	>

<channel>
	<title>.Net Smoothie &#187; Aggregate</title>
	<atom:link href="http://www.richardbushnell.net/tag/aggregate/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.richardbushnell.net</link>
	<description></description>
	<lastBuildDate>Wed, 30 Dec 2009 11:42:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Refactoring C# Series: Aggregation of IEnumerable</title>
		<link>http://www.richardbushnell.net/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/</link>
		<comments>http://www.richardbushnell.net/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/#comments</comments>
		<pubDate>Sun, 02 Mar 2008 20:54:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 2.0]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Accumulator]]></category>
		<category><![CDATA[Aggregate]]></category>
		<category><![CDATA[Lambda Expressions]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/</guid>
		<description><![CDATA[I was recently reading Programming Ruby: The Pragmatic Programmers&#8217; Guide, Second Edition, and came across this piece of example Ruby code: [1,3,5,7].inject(0) {&#124;sum, element&#124; sum+element} -&#62; 16 [1,3,5,7].inject(1) {&#124;product, element&#124; product*element} -&#62; 105 Inject is a method which acts on an array by aggregating or accumulating the values within that array. It loops through the [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F02%2Frefactoring-c-series-aggregation-of-ienumerable%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p><a href="http://www.amazon.com/gp/product/0974514055?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0974514055"><img style="margin: 0px 20px 20px 0px" src="/images/21VJS5BMKVL._AA_SL160_.jpg" align="left" border="0" /></a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0974514055" width="1" border="0" /></p>
<p>I was recently reading <a href="http://www.amazon.com/gp/product/0974514055?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0974514055">Programming Ruby: The Pragmatic Programmers&#8217; Guide, Second Edition</a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0974514055" width="1" border="0" />, and came across this piece of example Ruby code:</p>
<blockquote><p>[1,3,5,7].inject(0) {|sum, element| sum+element} -&gt; 16      <br />[1,3,5,7].inject(1) {|product, element| product*element} -&gt; 105</p>
</blockquote>
<p><strong>Inject</strong> is a method which acts on an array by <em>aggregating</em> or <em>accumulating</em> the values within that array. It loops through the array, and for every item in the array, it performs a function. It then saves the result for the next iteration of the loop and eventually returns the aggregated value.</p>
<p>In <strong>C# 1.0</strong> you would probably write such a method like this:</p>
<pre class="code"><span style="color: blue">int </span>sum = 0;
<span style="color: blue">int</span>[] list = <span style="color: blue">new int</span>[] { 1, 3, 5, 7 };
<span style="color: blue">foreach </span>(<span style="color: blue">int </span>item <span style="color: blue">in </span>list)
{
  <span style="color: green">// Perform some function, then save the result
  </span>sum = sum + item;
}</pre>
<p>It&#8217;s a bit long-winded, and if you wanted to make it reusable, you&#8217;d have a hard time.</p>
<p>In C# 3.0, you can do it just like you can in Ruby.</p>
<p><span id="more-60"></span></p>
<h2>Defining the Aggregation</h2>
<p>First, let me explain how the Ruby <strong>inject </strong>method works.</p>
<p>First of all, it&#8217;s really misnamed in Ruby. The method is an aggregator, or even an &quot;accumulator&quot;. It aggregates or accumulates values. It takes two parameters &#8211; a starter value, and a block. In C# 3.0 we basically call a block a delegate, although in this case, it&#8217;s more like a Lambda Expression.</p>
<p>The <strong>inject</strong> method works like this:</p>
<ol>
<li>it takes the starter parameter and sets the aggregated value (the <strong>sum</strong> in the above example) to its value. </li>
<li>For the first item in the array, it passes the tarter value and the item itself to the block, which then performs the defined function on it. </li>
<li>The return value from the block is then assigned to the running aggregated value. </li>
<li>The running aggregated value is passed into the next iteration with the next item from the list. The function is called on those items again. </li>
<li>When the method has iterated over all items in the list, it returns the aggregated value. </li>
</ol>
<h2>Moving to C# 2.0</h2>
<p>So, let&#8217;s imagine you were trying to write the <strong>Inject </strong>method in <strong>C# 2.0</strong>. If you were to refactor the above <strong>C# 1.0</strong> example as <strong>C# 2.0</strong>, you might use anonymous methods to write this:</p>
<pre class="code"><span style="color: green">// Define a delegate
</span><span style="color: blue">delegate int </span><span style="color: #2b91af">Aggregator</span>(<span style="color: blue">int </span>sum, <span style="color: blue">int </span>item);

<span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args) {

  <span style="color: blue">int </span>sum = 0;
  <span style="color: blue">int</span>[] list = <span style="color: blue">new int</span>[] { 1, 3, 5, 7 };

  sum = Inject(sum, list,     <span style="color: blue">delegate</span>(<span style="color: blue">int </span>starterVal, <span style="color: blue">int </span>item) {
      <span style="color: blue">return </span>starterVal + item;
    });
}

<span style="color: blue">int </span>Inject(<span style="color: blue">int </span>starterVal, <span style="color: blue">int</span>[] list,
           <span style="color: #2b91af">Aggregator </span>aggregator) {
  <span style="color: blue">int </span>sum = starterVal;
  <span style="color: blue">foreach </span>(<span style="color: blue">int </span>item <span style="color: blue">in </span>list) {
    <span style="color: green">// Perform some function, then save the result
    </span>sum = aggregator(sum, item);
  }
  <span style="color: blue">return </span>sum;</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>However, that would only work for <strong>int</strong> objects. You could really make it generic, and use the same method for other types:</p>
<pre class="code"><span style="color: green">// Define a delegate
</span><span style="color: blue">delegate </span>T <span style="color: #2b91af">Aggregator</span>&lt;T&gt;(T sum, T item);

<span style="color: blue">...</span></pre>
<p>
  </p>
<pre class="code"><span style="color: blue"></span>  sum = Inject&lt;<span style="color: blue">int</span>&gt;(sum, list,
     <span style="color: blue">delegate</span>(<span style="color: blue">int </span>starterVal, <span style="color: blue">int </span>item) {
      <span style="color: blue">return </span>starterVal + item;
    });</pre>
<p>
  </p>
<pre class="code">...

T Inject&lt;T&gt;(T starterVal, T[] list,
  <span style="color: #2b91af">Aggregator</span>&lt;T&gt; aggregator) {
  T sum = starterVal;
  <span style="color: blue">foreach </span>(T item <span style="color: blue">in </span>list) {
    <span style="color: green">// Perform some function, then save the result
    </span>sum = aggregator(sum, item);
  }
  <span style="color: blue">return </span>sum;
}</pre>
<p>It&#8217;s nicer, but the Ruby method still wins hands-down for neatness.</p>
<h2>Move Over Ruby, Here Comes C# 3.0</h2>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The good news is, the C# 3.0 compiler and the .Net 3.5 framework can now take care of most of this for you.</p>
<p>To start with, the Aggregator delegate is no longer necessary, because the new <strong>Func&lt;T,T,T&gt;</strong> delegate already defines a generic delegate which returns a value.</p>
<pre class="code">T Inject&lt;T&gt;(T starterVal, T[] list, <span style="color: #2b91af">Func</span>&lt;T,T,T&gt; aggregator)</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Secondly, the anonymous function using the delegate keyword can be replaced by a lambda expression like this:</p>
<pre class="code">(starterVal, item) =&gt; starterVal + item</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Thirdly, the Inject method can be defined as an extension method so that you can call it like this:</p>
<pre class="code">sum = list.Inject(sum, (starterVal, item) =&gt; starterVal + item );</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And fourthly, the compiler can infer the type for you, so you don&#8217;t need to specify it on calling the method.</p>
<h2>The Aggregate Method</h2>
<p>But the <em>even better news</em> is that this method is already defined in the .Net framework for you, so you don&#8217;t even have to write it. Instead of being called <strong>inject</strong>, it&#8217;s called <strong>Aggregate</strong>, and is defined on the <strong>System.Linq.Enumerable&lt;T&gt;</strong> class.</p>
<p>So basically, using C# 3.0, you could reduce the above code to this:</p>
<pre class="code"><span style="color: blue">var </span>sum = 0;
<span style="color: blue">var </span>list = <span style="color: blue">new</span>[] { 1, 3, 5, 7 };
sum = list.Aggregate(sum,
                     (starterVal, item) =&gt; starterVal + item );</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You get an extra bonus point if you spotted the extra C# 3.0 features I sneaked in there &#8211; the var keyword, and array initializers.</p>
<p>C# 3.0 is pretty neat huh? Move over Ruby.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F02%2Frefactoring-c-series-aggregation-of-ienumerable%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

