<p>How do I get the key of the current element in a <code>foreach</code> loop in C#?</p>

<p>For example:</p>

<h2>PHP</h2>

<pre><code>foreach ($array as $key =&gt; $value)
{
    echo("$value is assigned to key: $key");
}
</code></pre>

<h3>What I'm trying to do in C#:</h3>

<pre><code>int[] values = { 5, 14, 29, 49, 99, 150, 999 };

foreach (int val in values)
{
    if(search &lt;= val &amp;&amp; !stop)
    {
         // Set key to a variable
    }
}
</code></pre>

[{'answer_id': 60035, 'author': 'Jonathan Allen', 'author_id': 5274, 'author_profile': 'https://Stackoverflow.com/users/5274', 'pm_score': 2, 'selected': False, 'text': '<p>Alas there is no built-in way to do this. Either use a for loop or create a temp variable that you increment on each pass.</p>\n'}, {'answer_id': 60047, 'author': 'Billy Jo', 'author_id': 3447, 'author_profile': 'https://Stackoverflow.com/users/3447', 'pm_score': -1, 'selected': False, 'text': '<p><code>myKey = Array.IndexOf(values, val);</code></p>\n'}, {'answer_id': 60058, 'author': 'Tyler', 'author_id': 5642, 'author_profile': 'https://Stackoverflow.com/users/5642', 'pm_score': 5, 'selected': False, 'text': '<p>If you want to get at the key (read: index) then you\'d have to use a for loop. If you actually want to have a collection that holds keys/values then I\'d consider using a HashTable or a Dictionary (if you want to use Generics).</p>\n\n<pre><code>Dictionary&lt;int, string&gt; items = new  Dictionary&lt;int, string&gt;();\n\nforeach (int key in items.Keys)\n{\n  Console.WriteLine("Key: {0} has value: {1}", key, items[key]);\n}\n</code></pre>\n\n<p>Hope that helps,\nTyler</p>\n'}, {'answer_id': 60062, 'author': 'huseyint', 'author_id': 39, 'author_profile': 'https://Stackoverflow.com/users/39', 'pm_score': 2, 'selected': False, 'text': '<p>Actually you should use classic for (;;) loop if you want to loop through an array. But the similar functionality that you have achieved with your PHP code can be achieved in C# like this with a Dictionary:</p>\n\n<pre><code>Dictionary&lt;int, int&gt; values = new Dictionary&lt;int, int&gt;();\nvalues[0] = 5;\nvalues[1] = 14;\nvalues[2] = 29;\nvalues[3] = 49;\n// whatever...\n\nforeach (int key in values.Keys)\n{\n    Console.WriteLine("{0} is assigned to key: {1}", values[key], key);\n}\n</code></pre>\n'}, {'answer_id': 60089, 'author': 'Chris Ammerman', 'author_id': 2729, 'author_profile': 'https://Stackoverflow.com/users/2729', 'pm_score': 6, 'selected': True, 'text': '<p><a href="https://stackoverflow.com/questions/60032/getting-the-array-key-in-a-foreach-loop#60035">Grauenwolf\'s way</a> is the most straightforward and performant way of doing this with an array:</p>\n\n<blockquote>\n  <p>Either use a for loop or create a temp variable that you increment on each pass.</p>\n</blockquote>\n\n<p>Which would of course look like this:</p>\n\n<pre><code>int[] values = { 5, 14, 29, 49, 99, 150, 999 };\n\nfor (int key = 0; key &lt; values.Length; ++key)\n  if (search &lt;= values[key] &amp;&amp; !stop)\n  {\n    // set key to a variable\n  }\n</code></pre>\n\n<p>With .NET 3.5 you can take a more functional approach as well, but it is a little more verbose at the site, and would likely rely on a couple <a href="http://en.wikipedia.org/wiki/Apply" rel="noreferrer">support functions</a> for <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="noreferrer">visiting</a> the elements in an IEnumerable.  Overkill if this is all you need it for, but handy if you tend to do a lot of collection processing.</p>\n'}, {'answer_id': 60097, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<p>I answered this in another version of this question:</p>\n\n<blockquote>\n  <p>Foreach is for iterating over\n  collections that implement\n  IEnumerable. It does this by calling\n  GetEnumerator on the collection, which\n  will return an Enumerator.</p>\n  \n  <p>This Enumerator has a method and a\n  property:</p>\n\n<pre><code>* MoveNext()\n* Current\n</code></pre>\n  \n  <p>Current returns the object that\n  Enumerator is currently on, MoveNext\n  updates Current to the next object.</p>\n  \n  <p>Obviously, the concept of an index is\n  foreign to the concept of enumeration,\n  and cannot be done.</p>\n  \n  <p>Because of that, most collections are\n  able to be traversed using an indexer\n  and the for loop construct.</p>\n  \n  <p>I greatly prefer using a for loop in\n  this situation compared to tracking\n  the index with a local variable.</p>\n</blockquote>\n\n<p><a href="https://stackoverflow.com/questions/43021/c-get-index-of-current-foreach-iteration#43029">How do you get the index of the current iteration of a foreach loop?</a></p>\n'}, {'answer_id': 1984058, 'author': 'mat3', 'author_id': 173472, 'author_profile': 'https://Stackoverflow.com/users/173472', 'pm_score': 0, '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': 1984176, 'author': 'Craig Gidney', 'author_id': 52239, 'author_profile': 'https://Stackoverflow.com/users/52239', 'pm_score': 0, 'selected': False, 'text': '<p>You can implement this functionality yourself using an extension method. For example, here is an implementation of an extension method KeyValuePairs which works on lists:</p>\n\n<pre><code>public struct IndexValue&lt;T&gt; {\n    public int Index {get; private set;}\n    public T Value {get; private set;}\n    public IndexValue(int index, T value) : this() {\n        this.Index = index;\n        this.Value = value;\n    }\n}\n\npublic static class EnumExtension\n{\n    public static IEnumerable&lt;IndexValue&lt;T&gt;&gt; KeyValuePairs&lt;T&gt;(this IList&lt;T&gt; list) {\n        for (int i = 0; i &lt; list.Count; i++)\n            yield return new IndexValue&lt;T&gt;(i, list[i]);\n    }\n}\n</code></pre>\n'}, {'answer_id': 7366406, 'author': 'Guillaume Massé', 'author_id': 449071, 'author_profile': 'https://Stackoverflow.com/users/449071', 'pm_score': 4, 'selected': False, 'text': '<p>With DictionaryEntry and KeyValuePair:</p>\n\n<p>Based on<br>\n<a href="http://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry.aspx" rel="noreferrer">MSDN</a></p>\n\n<pre><code>IDictionary&lt;string,string&gt; openWith = new Dictionary&lt;string,string&gt;()\n{\n   { "txt", "notepad.exe" }\n   { "bmp", "paint.exe" }\n   { "rtf", "wordpad.exe" }\n};\n\nforeach (DictionaryEntry de in openWith)\n{\n    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);\n}\n\n// also\n\nforeach (KeyValuePair&lt;string,string&gt; de in openWith)\n{\n    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);\n}\n</code></pre>\n\n<p><a href="https://stackoverflow.com/questions/905424/keyvaluepair-vs-dictionaryentry">Releated SO question: KeyValuePair VS DictionaryEntry</a></p>\n'}]
['https://Stackoverflow.com/questions/60032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2025/']