<p>Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?</p>

<p>For instance, I currently do something like this depending on the circumstances:</p>

<pre><code>int i = 0;
foreach (Object o in collection)
{
    // ...
    i++;
}
</code></pre>

[{'answer_id': 43026, 'author': 'Joseph Daigle', 'author_id': 507, 'author_profile': 'https://Stackoverflow.com/users/507', 'pm_score': 2, 'selected': False, 'text': '<p>Unless your collection can return the index of the object via some method, the only way is to use a counter like in your example.</p>\n\n<p>However, when working with indexes, the only reasonable answer to the problem is to use a for loop. Anything else introduces code complexity, not to mention time and space complexity.</p>\n'}, {'answer_id': 43028, 'author': 'bryansh', 'author_id': 211367, 'author_profile': 'https://Stackoverflow.com/users/211367', 'pm_score': 2, 'selected': False, 'text': "<p>I don't believe there is a way to get the value of the current iteration of a foreach loop.  Counting yourself, seems to be the best way.</p>\n\n<p>May I ask, why you would want to know?</p>\n\n<p>It seems that you would most likley be doing one of three things:</p>\n\n<p>1)  Getting the object from the collection, but in this case you already have it.</p>\n\n<p>2)  Counting the objects for later post processing...the collections have a Count property that you could make use of.</p>\n\n<p>3)  Setting a property on the object based on its order in the loop...although you could easily be setting that when you added the object to the collection.</p>\n"}, {'answer_id': 43029, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 10, 'selected': True, 'text': '<p>The <code>foreach</code> is for iterating over collections that implement <a href="http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx" rel="noreferrer"><code>IEnumerable</code></a>. It does this by calling <a href="http://msdn.microsoft.com/en-us/library/s793z9y2(v=vs.110).aspx" rel="noreferrer"><code>GetEnumerator</code></a> on the collection, which will return an <a href="http://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx" rel="noreferrer"><code>Enumerator</code></a>.</p>\n<p>This Enumerator has a method and a property:</p>\n<ul>\n<li><code>MoveNext()</code></li>\n<li><code>Current</code></li>\n</ul>\n<p><code>Current</code> returns the object that Enumerator is currently on, <code>MoveNext</code> updates <code>Current</code> to the next object.</p>\n<p>The concept of an index is foreign to the concept of enumeration, and cannot be done.</p>\n<p>Because of that, most collections are able to be traversed using an indexer and the for loop construct.</p>\n<p>I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.</p>\n'}, {'answer_id': 43035, 'author': 'Brad Wilson', 'author_id': 1554, 'author_profile': 'https://Stackoverflow.com/users/1554', 'pm_score': 7, 'selected': False, 'text': '<p>Could do something like this:</p>\n\n<pre><code>public static class ForEachExtensions\n{\n    public static void ForEachWithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, Action&lt;T, int&gt; handler)\n    {\n        int idx = 0;\n        foreach (T item in enumerable)\n            handler(item, idx++);\n    }\n}\n\npublic class Example\n{\n    public static void Main()\n    {\n        string[] values = new[] { "foo", "bar", "baz" };\n\n        values.ForEachWithIndex((item, idx) =&gt; Console.WriteLine("{0}: {1}", idx, item));\n    }\n}\n</code></pre>\n'}, {'answer_id': 43103, 'author': 'crucible', 'author_id': 3717, 'author_profile': 'https://Stackoverflow.com/users/3717', 'pm_score': 4, 'selected': False, 'text': "<p>It's only going to work for a List and not any IEnumerable, but in LINQ there's this:</p>\n\n<pre><code>IList&lt;Object&gt; collection = new List&lt;Object&gt; { \n    new Object(), \n    new Object(), \n    new Object(), \n    };\n\nforeach (Object o in collection)\n{\n    Console.WriteLine(collection.IndexOf(o));\n}\n\nConsole.ReadLine();\n</code></pre>\n\n<p>@Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :)</p>\n\n<p>@Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares.</p>\n\n<p>That said, List might keep an index of each object along with the count.</p>\n\n<p>Jonathan seems to have a better idea, if he would elaborate?</p>\n\n<p>It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable.</p>\n"}, {'answer_id': 77542, 'author': 'Amy B', 'author_id': 8155, 'author_profile': 'https://Stackoverflow.com/users/8155', 'pm_score': 6, 'selected': False, 'text': '<p>Literal Answer -- warning, performance may not be as good as just using an <code>int</code> to track the index.  At least it is better than using <code>IndexOf</code>.</p>\n\n<p>You just need to use the indexing overload of Select to wrap each item in the collection with an anonymous object that knows the index.  This can be done against anything that implements IEnumerable.</p>\n\n<pre><code>System.Collections.IEnumerable collection = Enumerable.Range(100, 10);\n\nforeach (var o in collection.OfType&lt;object&gt;().Select((x, i) =&gt; new {x, i}))\n{\n    Console.WriteLine("{0} {1}", o.i, o.x);\n}\n</code></pre>\n'}, {'answer_id': 1046748, 'author': 'mike nelson', 'author_id': 23616, 'author_profile': 'https://Stackoverflow.com/users/23616', 'pm_score': 7, 'selected': False, 'text': "<p>I disagree with comments that a <code>for</code> loop is a better choice in most cases. </p>\n\n<p><code>foreach</code> is a useful construct, and not replaceble by a <code>for</code> loop in all circumstances. </p>\n\n<p>For example, if you have a <strong>DataReader</strong> and loop through all records using a <code>foreach</code> it automatically calls the <strong>Dispose</strong> method and closes the reader (which can then close the connection automatically). This is therefore safer as it prevents connection leaks even if you forget to close the reader. </p>\n\n<p>(Sure it is good practise to always close readers but the compiler is not going to catch it if you don't - you can't guarantee you have closed all readers but you can make it more likely you won't leak connections by getting in the habit of using foreach.)</p>\n\n<p>There may be other examples of the implicit call of the <code>Dispose</code> method being useful.</p>\n"}, {'answer_id': 1984049, 'author': 'mat3', 'author_id': 173472, 'author_profile': 'https://Stackoverflow.com/users/173472', 'pm_score': 4, 'selected': False, 'text': "<p>Here's a solution I just came up with for this problem</p>\n\n<p><strong>Original code:</strong></p>\n\n<pre><code>int index=0;\nforeach (var item in enumerable)\n{\n    blah(item, index); // some code that depends on the index\n    index++;\n}\n</code></pre>\n\n<p><strong>Updated code</strong></p>\n\n<pre><code>enumerable.ForEach((item, index) =&gt; blah(item, index));\n</code></pre>\n\n<p><strong>Extension Method:</strong></p>\n\n<pre><code>    public static IEnumerable&lt;T&gt; ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, Action&lt;T, int&gt; action)\n    {\n        var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void\n        enumerable.Select((item, i) =&gt; \n            {\n                action(item, i);\n                return unit;\n            }).ToList();\n\n        return pSource;\n    }\n</code></pre>\n"}, {'answer_id': 1985112, 'author': 'Sachin', 'author_id': 149656, 'author_profile': 'https://Stackoverflow.com/users/149656', 'pm_score': 3, 'selected': False, 'text': '<pre><code>int index;\nforeach (Object o in collection)\n{\n    index = collection.indexOf(o);\n}\n</code></pre>\n\n<p>This would work for collections supporting <code>IList</code>.</p>\n'}, {'answer_id': 3293486, 'author': 'Brian Gideon', 'author_id': 158779, 'author_profile': 'https://Stackoverflow.com/users/158779', 'pm_score': 5, 'selected': False, 'text': '<p>You could wrap the original enumerator with another that does contain the index information.</p>\n\n<pre><code>foreach (var item in ForEachHelper.WithIndex(collection))\n{\n    Console.Write("Index=" + item.Index);\n    Console.Write(";Value= " + item.Value);\n    Console.Write(";IsLast=" + item.IsLast);\n    Console.WriteLine();\n}\n</code></pre>\n\n<p>Here is the code for the <code>ForEachHelper</code> class.</p>\n\n<pre><code>public static class ForEachHelper\n{\n    public sealed class Item&lt;T&gt;\n    {\n        public int Index { get; set; }\n        public T Value { get; set; }\n        public bool IsLast { get; set; }\n    }\n\n    public static IEnumerable&lt;Item&lt;T&gt;&gt; WithIndex&lt;T&gt;(IEnumerable&lt;T&gt; enumerable)\n    {\n        Item&lt;T&gt; item = null;\n        foreach (T value in enumerable)\n        {\n            Item&lt;T&gt; next = new Item&lt;T&gt;();\n            next.Index = 0;\n            next.Value = value;\n            next.IsLast = false;\n            if (item != null)\n            {\n                next.Index = item.Index + 1;\n                yield return item;\n            }\n            item = next;\n        }\n        if (item != null)\n        {\n            item.IsLast = true;\n            yield return item;\n        }            \n    }\n}\n</code></pre>\n'}, {'answer_id': 3535307, 'author': 'user426810', 'author_id': 426810, 'author_profile': 'https://Stackoverflow.com/users/426810', 'pm_score': 3, 'selected': False, 'text': '<p>Better to use keyword <code>continue</code> safe construction like this</p>\n\n<pre><code>int i=-1;\nforeach (Object o in collection)\n{\n    ++i;\n    //...\n    continue; //&lt;--- safe to call, index will be increased\n    //...\n}\n</code></pre>\n'}, {'answer_id': 3535362, 'author': 'Ian Henry', 'author_id': 223274, 'author_profile': 'https://Stackoverflow.com/users/223274', 'pm_score': 3, 'selected': False, 'text': '<p>This is how I do it, which is nice for its simplicity/brevity, but if you\'re doing a lot in the loop body <code>obj.Value</code>, it is going to get old pretty fast.</p>\n\n<pre><code>foreach(var obj in collection.Select((item, index) =&gt; new { Index = index, Value = item }) {\n    string foo = string.Format("Something[{0}] = {1}", obj.Index, obj.Value);\n    ...\n}\n</code></pre>\n'}, {'answer_id': 3691283, 'author': 'ulrichb', 'author_id': 50890, 'author_profile': 'https://Stackoverflow.com/users/50890', 'pm_score': 2, 'selected': False, 'text': '<p>My solution for this problem is an extension method <code>WithIndex()</code>,</p>\n\n<p><a href="http://code.google.com/p/ub-dotnet-utilities/source/browse/trunk/Src/Utilities/Extensions/EnumerableExtensions.cs" rel="nofollow noreferrer">http://code.google.com/p/ub-dotnet-utilities/source/browse/trunk/Src/Utilities/Extensions/EnumerableExtensions.cs</a></p>\n\n<p><strong>Use it like</strong></p>\n\n<pre><code>var list = new List&lt;int&gt; { 1, 2, 3, 4, 5, 6 };    \n\nvar odd = list.WithIndex().Where(i =&gt; (i.Item &amp; 1) == 1);\nCollectionAssert.AreEqual(new[] { 0, 2, 4 }, odd.Select(i =&gt; i.Index));\nCollectionAssert.AreEqual(new[] { 1, 3, 5 }, odd.Select(i =&gt; i.Item));\n</code></pre>\n'}, {'answer_id': 4055002, 'author': 'Matt Towers', 'author_id': 491656, 'author_profile': 'https://Stackoverflow.com/users/491656', 'pm_score': 1, 'selected': False, 'text': '<p>How about something like this?  Note that myDelimitedString may be null if myEnumerable is empty.</p>\n\n<pre><code>IEnumerator enumerator = myEnumerable.GetEnumerator();\nstring myDelimitedString;\nstring current = null;\n\nif( enumerator.MoveNext() )\n    current = (string)enumerator.Current;\n\nwhile( null != current)\n{\n    current = (string)enumerator.Current; }\n\n    myDelimitedString += current;\n\n    if( enumerator.MoveNext() )\n        myDelimitedString += DELIMITER;\n    else\n        break;\n}\n</code></pre>\n'}, {'answer_id': 5405140, 'author': 'nicodemus13', 'author_id': 26463, 'author_profile': 'https://Stackoverflow.com/users/26463', 'pm_score': 2, 'selected': False, 'text': '<p>I just had this problem, but thinking around the problem in my case gave the best solution, unrelated to the expected solution.</p>\n\n<p>It could be quite a common case, basically, I\'m reading from one source list and creating objects based on them in a destination list, however, I have to check whether the source items are valid first and want to return the row of any error.  At first-glance, I want to get the index into the enumerator of the object at the Current property, however, as I am copying these elements, I implicitly know the current index anyway from the current destination.  Obviously it depends on your destination object, but for me it was a List, and most likely it will implement ICollection.</p>\n\n<p>i.e.</p>\n\n<pre><code>var destinationList = new List&lt;someObject&gt;();\nforeach (var item in itemList)\n{\n  var stringArray = item.Split(new char[] { \';\', \',\' }, StringSplitOptions.RemoveEmptyEntries);\n\n  if (stringArray.Length != 2)\n  {\n    //use the destinationList Count property to give us the index into the stringArray list\n    throw new Exception("Item at row " + (destinationList.Count + 1) + " has a problem.");\n  }\n  else\n  {\n    destinationList.Add(new someObject() { Prop1 = stringArray[0], Prop2 = stringArray[1]});\n  }\n}\n</code></pre>\n\n<p>Not always applicable, but often enough to be worth mentioning, I think.</p>\n\n<p>Anyway, the point being that sometimes there is a non-obvious solution already in the logic you have...</p>\n'}, {'answer_id': 5709974, 'author': 'Matt Mitchell', 'author_id': 364, 'author_profile': 'https://Stackoverflow.com/users/364', 'pm_score': 2, 'selected': False, 'text': '<p>For interest, Phil Haack just wrote an example of this in the context of a Razor Templated Delegate (<a href="http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx" rel="nofollow">http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx</a>)</p>\n\n<p>Effectively he writes an extension method which wraps the iteration in an "IteratedItem" class (see below) allowing access to the index as well as the element during iteration.</p>\n\n<pre><code>public class IndexedItem&lt;TModel&gt; {\n  public IndexedItem(int index, TModel item) {\n    Index = index;\n    Item = item;\n  }\n\n  public int Index { get; private set; }\n  public TModel Item { get; private set; }\n}\n</code></pre>\n\n<p>However, while this would be fine in a non-Razor environment if you are doing a single operation (i.e. one that could be provided as a lambda) it\'s not going to be a solid replacement of the for/foreach syntax in non-Razor contexts.</p>\n'}, {'answer_id': 7421615, 'author': 'Kasey Speakman', 'author_id': 209133, 'author_profile': 'https://Stackoverflow.com/users/209133', 'pm_score': 2, 'selected': False, 'text': '<p>I wasn\'t sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.</p>\n\n<pre><code>string[] names = { "one", "two", "three" };\nvar oddOrEvenByName = names\n    .Select((name, index) =&gt; new KeyValuePair&lt;string, int&gt;(name, index % 2))\n    .ToDictionary(kvp =&gt; kvp.Key, kvp =&gt; kvp.Value);\n</code></pre>\n\n<p>This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.</p>\n'}, {'answer_id': 11437562, 'author': 'bcahill', 'author_id': 474902, 'author_profile': 'https://Stackoverflow.com/users/474902', 'pm_score': 10, 'selected': False, 'text': '<p>Ian Mercer posted a similar solution as this on <a href="http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx" rel="noreferrer">Phil Haack\'s blog</a>:</p>\n<pre><code>foreach (var item in Model.Select((value, i) =&gt; new { i, value }))\n{\n    var value = item.value;\n    var index = item.i;\n}\n</code></pre>\n<p>This gets you the item (<code>item.value</code>) and its index (<code>item.i</code>) by using <a href="https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx" rel="noreferrer">this overload of LINQ\'s <code>Select</code></a>:</p>\n<blockquote>\n<p>the second parameter of the function [inside Select] represents the index of the source element.</p>\n</blockquote>\n<p>The <code>new { i, value }</code> is creating a new <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types" rel="noreferrer">anonymous object</a>.</p>\n<p>Heap allocations can be avoided by using <code>ValueTuple</code> if you\'re using C# 7.0 or later:</p>\n<pre><code>foreach (var item in Model.Select((value, i) =&gt; ( value, i )))\n{\n    var value = item.value;\n    var index = item.i;\n}\n</code></pre>\n<p>You can also eliminate the <code>item.</code> by using automatic destructuring:</p>\n<pre><code>foreach (var (value, i) in Model.Select((value, i) =&gt; ( value, i )))\n{\n    // Access `value` and `i` directly here.\n}\n</code></pre>\n'}, {'answer_id': 15572052, 'author': 'Bart Calixto', 'author_id': 826568, 'author_profile': 'https://Stackoverflow.com/users/826568', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think this should be quite efficient, but it works:</p>\n\n<pre><code>@foreach (var banner in Model.MainBanners) {\n    @Model.MainBanners.IndexOf(banner)\n}\n</code></pre>\n"}, {'answer_id': 15889868, 'author': 'mike nelson', 'author_id': 23616, 'author_profile': 'https://Stackoverflow.com/users/23616', 'pm_score': 0, 'selected': False, 'text': '<p>Here is another solution to this problem, with a focus on keeping the syntax as close to a standard <code>foreach</code> as possible. </p>\n\n<p>This sort of construct is useful if you are wanting to make your views look nice and clean in MVC. For example instead of writing this the usual way (which is hard to format nicely):</p>\n\n<pre><code> &lt;%int i=0;\n foreach (var review in Model.ReviewsList) { %&gt;\n    &lt;div id="review_&lt;%=i%&gt;"&gt;\n        &lt;h3&gt;&lt;%:review.Title%&gt;&lt;/h3&gt;                      \n    &lt;/div&gt;\n    &lt;%i++;\n } %&gt;\n</code></pre>\n\n<p>You could instead write this:</p>\n\n<pre><code> &lt;%foreach (var review in Model.ReviewsList.WithIndex()) { %&gt;\n    &lt;div id="review_&lt;%=LoopHelper.Index()%&gt;"&gt;\n        &lt;h3&gt;&lt;%:review.Title%&gt;&lt;/h3&gt;                      \n    &lt;/div&gt;\n &lt;%} %&gt;\n</code></pre>\n\n<p>I\'ve written some helper methods to enable this:</p>\n\n<pre><code>public static class LoopHelper {\n    public static int Index() {\n        return (int)HttpContext.Current.Items["LoopHelper_Index"];\n    }       \n}\n\npublic static class LoopHelperExtensions {\n    public static IEnumerable&lt;T&gt; WithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; that) {\n        return new EnumerableWithIndex&lt;T&gt;(that);\n    }\n\n    public class EnumerableWithIndex&lt;T&gt; : IEnumerable&lt;T&gt; {\n        public IEnumerable&lt;T&gt; Enumerable;\n\n        public EnumerableWithIndex(IEnumerable&lt;T&gt; enumerable) {\n            Enumerable = enumerable;\n        }\n\n        public IEnumerator&lt;T&gt; GetEnumerator() {\n            for (int i = 0; i &lt; Enumerable.Count(); i++) {\n                HttpContext.Current.Items["LoopHelper_Index"] = i;\n                yield return Enumerable.ElementAt(i);\n            }\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() {\n            return GetEnumerator();\n        }\n    }\n</code></pre>\n\n<p>In a non-web environment you could use a <code>static</code> instead of <code>HttpContext.Current.Items</code>.</p>\n\n<p>This is essentially a global variable, and so you cannot have more than one WithIndex loop nested, but that is not a major problem in this use case.</p>\n'}, {'answer_id': 19236156, 'author': 'Gezim', 'author_id': 32495, 'author_profile': 'https://Stackoverflow.com/users/32495', 'pm_score': 5, 'selected': False, 'text': '<p>Using @FlySwat\'s answer, I came up with this solution:</p>\n\n<pre><code>//var list = new List&lt;int&gt; { 1, 2, 3, 4, 5, 6 }; // Your sample collection\n\nvar listEnumerator = list.GetEnumerator(); // Get enumerator\n\nfor (var i = 0; listEnumerator.MoveNext() == true; i++)\n{\n  int currentItem = listEnumerator.Current; // Get current item.\n  //Console.WriteLine("At index {0}, item is {1}", i, currentItem); // Do as you wish with i and  currentItem\n}\n</code></pre>\n\n<p>You get the enumerator using <code>GetEnumerator</code> and then you loop using a <code>for</code> loop. However, the trick is to make the loop\'s condition <code>listEnumerator.MoveNext() == true</code>.</p>\n\n<p>Since the <code>MoveNext</code> method of an enumerator returns true if there is a next element and it can be accessed, making that the loop condition makes the loop stop when we run out of elements to iterate over.</p>\n'}, {'answer_id': 19594773, 'author': 'Warren LaFrance', 'author_id': 1404405, 'author_profile': 'https://Stackoverflow.com/users/1404405', 'pm_score': 2, 'selected': False, 'text': '<p>I built this in <a href="https://en.wikipedia.org/wiki/LINQPad" rel="nofollow">LINQPad</a>:</p>\n\n<pre><code>var listOfNames = new List&lt;string&gt;(){"John","Steve","Anna","Chris"};\n\nvar listCount = listOfNames.Count;\n\nvar NamesWithCommas = string.Empty;\n\nforeach (var element in listOfNames)\n{\n    NamesWithCommas += element;\n    if(listOfNames.IndexOf(element) != listCount -1)\n    {\n        NamesWithCommas += ", ";\n    }\n}\n\nNamesWithCommas.Dump();  //LINQPad method to write to console.\n</code></pre>\n\n<p>You could also just use <code>string.join</code>:</p>\n\n<pre><code>var joinResult = string.Join(",", listOfNames);\n</code></pre>\n'}, {'answer_id': 22016592, 'author': 'David Bullock', 'author_id': 463052, 'author_profile': 'https://Stackoverflow.com/users/463052', 'pm_score': 6, 'selected': False, 'text': '<p>There\'s nothing wrong with using a counter variable. In fact, whether you use <code>for</code>, <code>foreach</code> <code>while</code> or <code>do</code>, a counter variable must somewhere be declared and incremented.</p>\n\n<p>So use this idiom if you\'re not sure if you have a suitably-indexed collection:</p>\n\n<pre><code>var i = 0;\nforeach (var e in collection) {\n   // Do stuff with \'e\' and \'i\'\n   i++;\n}\n</code></pre>\n\n<p>Else use this one if you <em>know</em> that your <em>indexable</em> collection is O(1) for index access (which it will be for <code>Array</code> and probably for <code>List&lt;T&gt;</code> (the documentation doesn\'t say), but not necessarily for other types (such as <code>LinkedList</code>)):</p>\n\n<pre><code>// Hope the JIT compiler optimises read of the \'Count\' property!\nfor (var i = 0; i &lt; collection.Count; i++) {\n   var e = collection[i];\n   // Do stuff with \'e\' and \'i\'\n}\n</code></pre>\n\n<p>It should never be necessary to \'manually\' operate the <code>IEnumerator</code> by invoking <code>MoveNext()</code> and interrogating <code>Current</code> - <code>foreach</code> is saving you that particular bother ... if you need to skip items, just use a <code>continue</code> in the body of the loop.</p>\n\n<p>And just for completeness, depending on what you were <em>doing</em> with your index (the above constructs offer plenty of flexibility), you might use Parallel LINQ:</p>\n\n<pre><code>// First, filter \'e\' based on \'i\',\n// then apply an action to remaining \'e\'\ncollection\n    .AsParallel()\n    .Where((e,i) =&gt; /* filter with e,i */)\n    .ForAll(e =&gt; { /* use e, but don\'t modify it */ });\n\n// Using \'e\' and \'i\', produce a new collection,\n// where each element incorporates \'i\'\ncollection\n    .AsParallel()\n    .Select((e, i) =&gt; new MyWrapper(e, i));\n</code></pre>\n\n<p>We use <code>AsParallel()</code> above, because it\'s 2014 already, and we want to make good use of those multiple cores to speed things up. Further, for \'sequential\' LINQ, <a href="https://stackoverflow.com/questions/101265/why-is-there-not-a-foreach-extension-method-on-the-ienumerable-interface">you only get a <code>ForEach()</code> extension method on <code>List&lt;T&gt;</code> and <code>Array</code></a> ... and it\'s not clear that using it is any better than doing a simple <code>foreach</code>, since you are still running single-threaded for uglier syntax.</p>\n'}, {'answer_id': 27785300, 'author': 'ssaeed', 'author_id': 3256077, 'author_profile': 'https://Stackoverflow.com/users/3256077', 'pm_score': 2, 'selected': False, 'text': '<p>If the collection is a list, you can use List.IndexOf, as in:</p>\n\n<pre><code>foreach (Object o in collection)\n{\n    // ...\n    @collection.IndexOf(o)\n}\n</code></pre>\n'}, {'answer_id': 33508983, 'author': 'BenKoshy', 'author_id': 4880924, 'author_profile': 'https://Stackoverflow.com/users/4880924', 'pm_score': 0, 'selected': False, 'text': '<p>This doesn\'t answer your specific question, but it DOES provide you with a solution to your problem: use a for loop to run through the object collection. then you will have the current index you are working on.</p>\n\n<pre><code>// Untested\nfor (int i = 0; i &lt; collection.Count; i++)\n{\n    Console.WriteLine("My index is " + i);\n}\n</code></pre>\n'}, {'answer_id': 37471479, 'author': 'Parsa', 'author_id': 2116114, 'author_profile': 'https://Stackoverflow.com/users/2116114', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Why foreach ?!</strong></p>\n\n<p>The simplest way is using <strong>for</strong> instead of foreach <strong>if you are using List</strong>:</p>\n\n<pre><code>for (int i = 0 ; i &lt; myList.Count ; i++)\n{\n    // Do something...\n}\n</code></pre>\n\n<p>Or if you want use foreach:</p>\n\n<pre><code>foreach (string m in myList)\n{\n     // Do something...\n}\n</code></pre>\n\n<p>You can use this to know the index of each loop:</p>\n\n<pre><code>myList.indexOf(m)\n</code></pre>\n'}, {'answer_id': 39105631, 'author': 'Satisfied', 'author_id': 6748675, 'author_profile': 'https://Stackoverflow.com/users/6748675', 'pm_score': 3, 'selected': False, 'text': '<p>You can write your loop like this:</p>\n\n<pre><code>var s = "ABCDEFG";\nforeach (var item in s.GetEnumeratorWithIndex())\n{\n    System.Console.WriteLine("Character: {0}, Position: {1}", item.Value, item.Index);\n}\n</code></pre>\n\n<p>After adding the following struct and extension method.</p>\n\n<p>The struct and extension method encapsulate Enumerable.Select functionality.</p>\n\n<pre><code>public struct ValueWithIndex&lt;T&gt;\n{\n    public readonly T Value;\n    public readonly int Index;\n\n    public ValueWithIndex(T value, int index)\n    {\n        this.Value = value;\n        this.Index = index;\n    }\n\n    public static ValueWithIndex&lt;T&gt; Create(T value, int index)\n    {\n        return new ValueWithIndex&lt;T&gt;(value, index);\n    }\n}\n\npublic static class ExtensionMethods\n{\n    public static IEnumerable&lt;ValueWithIndex&lt;T&gt;&gt; GetEnumeratorWithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable)\n    {\n        return enumerable.Select(ValueWithIndex&lt;T&gt;.Create);\n    }\n}\n</code></pre>\n'}, {'answer_id': 39997157, 'author': 'user1414213562', 'author_id': 6659843, 'author_profile': 'https://Stackoverflow.com/users/6659843', 'pm_score': 9, 'selected': False, 'text': '<p>Finally C#7 has a decent syntax for getting an index inside of a <code>foreach</code> loop (i. e. tuples):</p>\n<pre><code>foreach (var (item, index) in collection.WithIndex())\n{\n    Debug.WriteLine($&quot;{index}: {item}&quot;);\n}\n</code></pre>\n<p>A little extension method would be needed:</p>\n<pre><code>using System.Collections.Generic;\n\npublic static class EnumExtension {\n    public static IEnumerable&lt;(T item, int index)&gt; WithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; self)       \n       =&gt; self.Select((item, index) =&gt; (item, index));\n}\n</code></pre>\n'}, {'answer_id': 40540985, 'author': 'Kind Contributor', 'author_id': 887092, 'author_profile': 'https://Stackoverflow.com/users/887092', 'pm_score': 4, 'selected': False, 'text': '<p>This answer: lobby the C# language team for direct language support.</p>\n\n<p>The leading answer states:</p>\n\n<blockquote>\n  <p>Obviously, the concept of an index is foreign to the concept of\n  enumeration, and cannot be done.</p>\n</blockquote>\n\n<p>While this is true of the current C# language version (2020), this is not a conceptual CLR/Language limit, it can be done.</p>\n\n<p>The Microsoft C# language development team could create a new C# language feature, by adding support for a new Interface IIndexedEnumerable</p>\n\n<pre><code>foreach (var item in collection with var index)\n{\n    Console.WriteLine("Iteration {0} has value {1}", index, item);\n}\n\n//or, building on @user1414213562\'s answer\nforeach (var (item, index) in collection)\n{\n    Console.WriteLine("Iteration {0} has value {1}", index, item);\n}\n</code></pre>\n\n<p>If <code>foreach ()</code> is used and <code>with var index</code> is present, then the compiler expects the item collection to declare <code>IIndexedEnumerable</code> interface. If the interface is absent, the compiler can polyfill wrap the source with an IndexedEnumerable object, which adds in the code for tracking the index.</p>\n\n<pre><code>interface IIndexedEnumerable&lt;T&gt; : IEnumerable&lt;T&gt;\n{\n    //Not index, because sometimes source IEnumerables are transient\n    public long IterationNumber { get; }\n}\n</code></pre>\n\n<p>Later, the CLR can be updated to have internal index tracking, that is only used if <code>with</code> keyword is specified and the source doesn\'t directly implement <code>IIndexedEnumerable</code></p>\n\n<p>Why:</p>\n\n<ul>\n<li>Foreach looks nicer, and in business applications, foreach loops are rarely a performance bottleneck</li>\n<li>Foreach can be more efficient on memory. Having a pipeline of functions instead of converting to new collections at each step. Who cares if it uses a few more CPU cycles when there are fewer CPU cache faults and fewer garbage collections?</li>\n<li>Requiring the coder to add index-tracking code, spoils the beauty</li>\n<li>It\'s quite easy to implement (please Microsoft) and is backward compatible</li>\n</ul>\n\n<p>While most people here are not Microsoft employees, this is <em>a</em> correct answer, you can lobby Microsoft to add such a feature. You could already build your own iterator with an <a href="https://stackoverflow.com/a/39997157/887092">extension function and use tuples</a>, but Microsoft could sprinkle the syntactic sugar to avoid the extension function</p>\n'}, {'answer_id': 45239493, 'author': 'Paul Mitchell', 'author_id': 38966, 'author_profile': 'https://Stackoverflow.com/users/38966', 'pm_score': 4, 'selected': False, 'text': '<p>C# 7 finally gives us an elegant way to do this:</p>\n\n<pre><code>static class Extensions\n{\n    public static IEnumerable&lt;(int, T)&gt; Enumerate&lt;T&gt;(\n        this IEnumerable&lt;T&gt; input,\n        int start = 0\n    )\n    {\n        int i = start;\n        foreach (var t in input)\n        {\n            yield return (i++, t);\n        }\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var s = new string[]\n        {\n            "Alpha",\n            "Bravo",\n            "Charlie",\n            "Delta"\n        };\n\n        foreach (var (i, t) in s.Enumerate())\n        {\n            Console.WriteLine($"{i}: {t}");\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 46145503, 'author': 'Pavel', 'author_id': 3553138, 'author_profile': 'https://Stackoverflow.com/users/3553138', 'pm_score': 6, 'selected': False, 'text': '<p>Using LINQ, C# 7, and the <code>System.ValueTuple</code> NuGet package, you can do this:</p>\n\n\n\n<pre class="lang-cs prettyprint-override"><code>foreach (var (value, index) in collection.Select((v, i)=&gt;(v, i))) {\n    Console.WriteLine(value + " is at index " + index);\n}\n</code></pre>\n\n<p>You can use the regular <code>foreach</code> construct and be able to access the value and index directly, not as a member of an object, and keeps both fields only in the scope of the loop. For these reasons, I believe this is the best solution if you are able to use C# 7 and <code>System.ValueTuple</code>.</p>\n'}, {'answer_id': 50456510, 'author': 'conterio', 'author_id': 4525819, 'author_profile': 'https://Stackoverflow.com/users/4525819', 'pm_score': 5, 'selected': False, 'text': '<p>Just add your own index. Keep it simple.</p>\n<pre><code>int i = -1;\nforeach (var item in Collection)\n{\n    ++i;\n    item.index = i;\n}\n</code></pre>\n'}, {'answer_id': 53789000, 'author': 'Ahmed Fwela', 'author_id': 4009642, 'author_profile': 'https://Stackoverflow.com/users/4009642', 'pm_score': -1, 'selected': False, 'text': '<p>i want to discuss this question more theoretically (since it has already enough practical answers)</p>\n\n<p>.net has a very nice abstraction model for groups of data (a.k.a. collections) </p>\n\n<ul>\n<li>At the very top, and the most abstract, you have an <code>IEnumerable</code> it\'s just a group of data that you can enumerate. It doesn\'t matter HOW you enumerate, it\'s just that you can enumerate some data. And that enumeration is done by a completely different object, an <code>IEnumerator</code></li>\n</ul>\n\n<p>these interfaces are defined is as follows:</p>\n\n<pre><code>//\n// Summary:\n//     Exposes an enumerator, which supports a simple iteration over a non-generic collection.\npublic interface IEnumerable\n{\n    //\n    // Summary:\n    //     Returns an enumerator that iterates through a collection.\n    //\n    // Returns:\n    //     An System.Collections.IEnumerator object that can be used to iterate through\n    //     the collection.\n    IEnumerator GetEnumerator();\n}\n\n//\n// Summary:\n//     Supports a simple iteration over a non-generic collection.\npublic interface IEnumerator\n{\n    //\n    // Summary:\n    //     Gets the element in the collection at the current position of the enumerator.\n    //\n    // Returns:\n    //     The element in the collection at the current position of the enumerator.\n    object Current { get; }\n\n    //\n    // Summary:\n    //     Advances the enumerator to the next element of the collection.\n    //\n    // Returns:\n    //     true if the enumerator was successfully advanced to the next element; false if\n    //     the enumerator has passed the end of the collection.\n    //\n    // Exceptions:\n    //   T:System.InvalidOperationException:\n    //     The collection was modified after the enumerator was created.\n    bool MoveNext();\n    //\n    // Summary:\n    //     Sets the enumerator to its initial position, which is before the first element\n    //     in the collection.\n    //\n    // Exceptions:\n    //   T:System.InvalidOperationException:\n    //     The collection was modified after the enumerator was created.\n    void Reset();\n}\n</code></pre>\n\n<ul>\n<li><p>as you might have noticed, the <code>IEnumerator</code> interface doesn\'t "know" what an index is, it just knows what element it\'s currently pointing to, and how to move to the next one.</p></li>\n<li><p>now here is the trick: <code>foreach</code> considers every input collection an <code>IEnumerable</code>, even if it is a more concrete implementation like an <code>IList&lt;T&gt;</code> (which inherits from <code>IEnumerable</code>), it will only see the abstract interface <code>IEnumerable</code>.</p></li>\n<li><p>what <code>foreach</code> is actually doing, is calling <code>GetEnumerator</code> on the collection, and calling <code>MoveNext</code> until it returns false.</p></li>\n<li><p>so here is the problem, you want to define a concrete concept "Indices" on an abstract concept "Enumerables", the built in <code>foreach</code> construct doesn\'t give you that option, so your only way is to define it yourself, either by what you are doing originally (creating a counter manually) or just use an implementation of <code>IEnumerator</code> that recognizes indices AND implement a <code>foreach</code> construct that recognizes that custom implementation.</p></li>\n</ul>\n\n<p>personally i would create an extension method like this</p>\n\n<pre><code>public static class Ext\n{\n    public static void FE&lt;T&gt;(this IEnumerable&lt;T&gt; l, Action&lt;int, T&gt; act)\n    {\n        int counter = 0;\n        foreach (var item in l)\n        {\n            act(counter, item);\n            counter++;\n        }\n    }\n}\n</code></pre>\n\n<p>and use it like this</p>\n\n<pre><code>var x = new List&lt;string&gt;() { "hello", "world" };\nx.FE((ind, ele) =&gt;\n{\n    Console.WriteLine($"{ind}: {ele}");\n});\n</code></pre>\n\n<p>this also avoids any unnecessary allocations seen in other answers.</p>\n'}, {'answer_id': 56218652, 'author': 'Marcos ruiz', 'author_id': 11475011, 'author_profile': 'https://Stackoverflow.com/users/11475011', 'pm_score': 2, 'selected': False, 'text': '<p>This way you can use the index and value using LINQ:</p>\n<pre><code>ListValues.Select((x, i) =&gt; new { Value = x, Index = i }).ToList().ForEach(element =&gt;\n{\n    // element.Index\n    // element.Value\n});\n</code></pre>\n'}, {'answer_id': 62951790, 'author': 'usman tahir', 'author_id': 5717287, 'author_profile': 'https://Stackoverflow.com/users/5717287', 'pm_score': 3, 'selected': False, 'text': '<pre><code>// using foreach loop how to get index number:\n    \nforeach (var result in results.Select((value, index) =&gt; new { index, value }))\n{\n    // do something\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/43021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364/']