在’foreach’循环中获取数组键

如何在C#的foreach循环中获取当前元素的键?

例如:

PHP

 foreach ($array as $key => $value) { echo("$value is assigned to key: $key"); } 

我想用C#做什么:

 int[] values = { 5, 14, 29, 49, 99, 150, 999 }; foreach (int val in values) { if(search <= val && !stop) { // Set key to a variable } } 

Grauenwolf的方式是使用数组执行此操作的最直接和最高效的方式 :

使用for循环或创建一个在每次传递时递增的临时变量。

这当然是这样的:

 int[] values = { 5, 14, 29, 49, 99, 150, 999 }; for (int key = 0; key < values.Length; ++key) if (search <= values[key] && !stop) { // set key to a variable } 

使用.NET 3.5,您也可以采用更实用的方法,但它在网站上更加冗长,并且可能依赖于一些支持函数来访问 IEnumerable中的元素。 如果这就是你需要它的全部技能,但是如果你倾向于进行大量的收集处理,那就太方便了。

如果你想获得密钥(读取:索引),那么你必须使用for循环。 如果你真的想拥有一个包含键/值的集合,那么我会考虑使用HashTable或Dictionary(如果你想使用Generics)。

 Dictionary items = new Dictionary(); foreach (int key in items.Keys) { Console.WriteLine("Key: {0} has value: {1}", key, items[key]); } 

希望有所帮助,泰勒

使用DictionaryEntry和KeyValuePair:

基于
MSDN

 IDictionary openWith = new Dictionary() { { "txt", "notepad.exe" } { "bmp", "paint.exe" } { "rtf", "wordpad.exe" } }; foreach (DictionaryEntry de in openWith) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } // also foreach (KeyValuePair de in openWith) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } 

发布的问题:KeyValuePair VS DictionaryEntry

唉,没有内置的方法来做到这一点。 使用for循环或创建一个在每次传递时递增的临时变量。

我在这个问题的另一个版本中回答了这个问题

Foreach用于迭代实现IEnumerable的集合。 它通过在集合上调用GetEnumerator来完成此操作,该集合将返回一个Enumerator。

此枚举器具有方法和属性:

 * MoveNext() * Current 

Current返回Enumerator当前所在的对象,MoveNext将Current更新为下一个对象。

显然,索引的概念对于枚举的概念来说是陌生的,并且无法完成。

因此,大多数集合都可以使用索引器和for循环结构遍历。

与使用局部变量跟踪索引相比,我更倾向于在这种情况下使用for循环。

你如何获得foreach循环的当前迭代的索引?

实际上,如果要循环遍历数组,则应该使用classic for(;;)循环。 但是你用PHP代码实现的类似function可以用C#实现,就像这样:

 Dictionary values = new Dictionary(); values[0] = 5; values[1] = 14; values[2] = 29; values[3] = 49; // whatever... foreach (int key in values.Keys) { Console.WriteLine("{0} is assigned to key: {1}", values[key], key); } 

您可以使用扩展方法自己实现此function。 例如,这是一个扩展方法KeyValuePairs的实现,它在列表上工作:

 public struct IndexValue { public int Index {get; private set;} public T Value {get; private set;} public IndexValue(int index, T value) : this() { this.Index = index; this.Value = value; } } public static class EnumExtension { public static IEnumerable> KeyValuePairs(this IList list) { for (int i = 0; i < list.Count; i++) yield return new IndexValue(i, list[i]); } } 

这是我刚刚提出的解决这个问题的解决方案

原始代码:

 int index=0; foreach (var item in enumerable) { blah(item, index); // some code that depends on the index index++; } 

更新的代码

 enumerable.ForEach((item, index) => blah(item, index)); 

扩展方法:

  public static IEnumerable ForEach(this IEnumerable enumerable, Action action) { 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 enumerable.Select((item, i) => { action(item, i); return unit; }).ToList(); return pSource; } 

myKey = Array.IndexOf(values, val);