<?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>Why Can&#039;t You Code? &#187; enumerable</title>
	<atom:link href="http://www.whycantyoucode.com/tag/enumerable/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.whycantyoucode.com</link>
	<description>The highest form of ignorance is when you reject something you don&#039;t know anything about.</description>
	<lastBuildDate>Thu, 25 Feb 2010 14:39:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Elegant foreach () with an index</title>
		<link>http://www.whycantyoucode.com/2009/11/elegant-foreach-with-an-index/</link>
		<comments>http://www.whycantyoucode.com/2009/11/elegant-foreach-with-an-index/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 14:43:00 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[elegant]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[foreach]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=39</guid>
		<description><![CDATA[I’ve seen various ways of handling the lack of support for an index in the foreach () construct over the years.
By far the most used strategy is to declare an index yourself and increment it at the end of every loop iteration. Let me demonstrate:
static void Main(string[] args)
{
    var range = Enumerable.Range(0, [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve seen various ways of handling the lack of support for an index in the foreach () construct over the years.</p>
<p>By far the most used strategy is to declare an index yourself and increment it at the end of every loop iteration. Let me demonstrate:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    int index = 0;
    foreach (int number in range)
    {
        Console.WriteLine(index + &quot; &quot; + number);
        index++;
    }

    // Output:
    // 0 0
    // 1 1
    // 2 2
}</pre>
<p>However, this becomes more of a problem if the code inside your loop conditionally breaks out of the loop, or if you need to use <code>continue;</code> to end the iteration early, requiring you to keep track of all of your exit points.</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    int index = 0;
    foreach (int number in range)
    {
        if (number &lt; 50) continue; // &lt;- oops, the index will be out of sync now. shouldn't have forgotten to increment it
        Console.WriteLine(index + &quot; &quot; + number);
        index ++;
    }

    // Output:
    // 0 50 (should be 50 50 – remember, this would be the 50th loop iteration, but it was ended early, before the index got a chance to be incremented)
    // 1 51 (should be 51 51)
    // 2 52 (should be 52 52)
}</pre>
<p>You can get rid of these problems with a little known overload for the Linq <a href="http://msdn.microsoft.com/en-us/library/bb534869.aspx" target="_blank">Enumerable.Select()</a> method which will supply the much needed index. <span style="color: #800000">Behold the uglyness:</span></p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    foreach (var c in range.Select((value, index) =&gt; new { Index = index, Value = value }))
    {
        if (c.Value &lt; 50) continue; // &lt;- the index will still be correct despite the early exit
        Console.WriteLine(c.Index + &quot; &quot; + c.Value);
    }

    // Output:
    // 50 50 (correct)
    // 51 51
    // 52 52
}</pre>
<p><strong><em>Damn code, you scary! (if you don’t want to get ate, see the elegant solution right below the video)</em></strong></p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:072a3fd2-20bd-48c2-badd-fe3f73212267" class="wlWriterEditableSmartContent">
<div><object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/dSBURkKin_8&amp;hl=en"></param><embed src="http://www.youtube.com/v/dSBURkKin_8&amp;hl=en" type="application/x-shockwave-flash" width="425" height="355"></embed></object></div>
</div>
<p>&#160;</p>
<p>Being someone who doesn’t particularly enjoy uglyness, I decided to wrap this into an extension method for <code>IEnumerable&lt;T&gt;</code>, so I can write this beautiful beautiful code below:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    foreach (var c in range.WithIndex())
    {
        if (c.Index % 2 == 0) continue; // &lt;- the index will still be correct despite the early exit

        Console.WriteLine(c.Index + &quot; &quot; + c.Value);
    }
}</pre>
<p><strong>You want your index to go backwards? </strong>Easy, an overload does all the dirty work, you can specify the value to start at and the step as parameters. The step can even be negative if you want!</p>
<pre class="brush:csharp">foreach (var c in range.WithIndex(range.Count(), –1)) { }</pre>
<p>Here’s the code listing for the extension method, enjoy:</p>
<pre class="brush: csharp;">public static class EnumerableWithIndexExtension
{
    public static IEnumerable&lt;ValueWithIndex&lt;T&gt;&gt; WithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable)
    {
        return enumerable.Select((value, index) =&gt; new ValueWithIndex&lt;T&gt;(value, index));
    }

    public static IEnumerable&lt;ValueWithIndex&lt;T&gt;&gt; WithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, int startAt, int step)
    {
        return enumerable.Select((value, index) =&gt; new ValueWithIndex&lt;T&gt;(value, startAt + index * step));
    }

    public class ValueWithIndex&lt;T&gt;
    {
        public int Index { get; private set; }
        public T Value { get; private set; }

        public ValueWithIndex(T value, int index)
        {
            Value = value;
            Index = index;
        }
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/elegant-foreach-with-an-index/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
