C# 在“foreach”循环中获取数组键

C# 在“foreach”循环中获取数组键,c#,arrays,C#,Arrays,如何在C中的foreach循环中获取当前元素的键 例如: PHP 我在C中尝试做的是: 唉,没有内在的方法来做到这一点。使用for循环或创建在每次传递时递增的临时变量。myKey=Array.IndexOfvalues,val 如果您想获得read:index键,那么必须使用for循环。如果你真的想拥有一个包含键/值的集合,那么如果你想使用泛型,我会考虑使用一个哈希表或一个字典。 Dictionary<int, string> items = new Dictionary<i

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

例如:

PHP 我在C中尝试做的是:
唉,没有内在的方法来做到这一点。使用for循环或创建在每次传递时递增的临时变量。

myKey=Array.IndexOfvalues,val

如果您想获得read:index键,那么必须使用for循环。如果你真的想拥有一个包含键/值的集合,那么如果你想使用泛型,我会考虑使用一个哈希表或一个字典。
Dictionary<int, string> items = new  Dictionary<int, string>();

foreach (int key in items.Keys)
{
  Console.WriteLine("Key: {0} has value: {1}", key, items[key]);
}
希望有帮助,
泰勒

事实上,你应该用经典来;;如果要在数组中循环,请执行循环。但是,您使用PHP代码实现的类似功能可以在C中通过字典实现:

Dictionary<int, int> values = new Dictionary<int, int>();
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);
}
是使用阵列执行此操作的最直接、最高效的方法:

使用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
  }

在.NET3.5中,您也可以采用更具功能性的方法,但在站点中会更详细一些,并且可能会依赖于IEnumerable中的几个元素。如果这就是你所需要的,那就太过分了,但是如果你倾向于做大量的收集处理,那就方便了。

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

Foreach用于在 实现 我数不清。它通过打电话来做到这一点 集合上的GetEnumerator,其中 将返回一个枚举数

此枚举数有一个方法和一个 财产:

* MoveNext()
* Current
Current返回 枚举器当前处于启用状态,请移动下一步 将当前对象更新到下一个对象

显然,索引的概念是 与枚举概念无关, 这是不可能做到的

因此,大多数收藏都是 可以使用索引器进行遍历 和for循环构造

我非常喜欢在中使用for循环 这种情况与跟踪相比 带有局部变量的索引


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

原始代码:

更新代码

扩展方法:


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

public struct IndexValue<T> {
    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<IndexValue<T>> KeyValuePairs<T>(this IList<T> list) {
        for (int i = 0; i < list.Count; i++)
            yield return new IndexValue<T>(i, list[i]);
    }
}

使用DictionaryEntry和KeyValuePair:

基于


那不是个好主意。Array.IndexOf基本上是一种搜索,最糟糕的情况是On。这样做n次,您的总体最坏情况会变成^2。用外行的话说,一个包含100个项目的数组最多可以进行10000次比较。撇开效率不谈,如果数组中有重复的项目,那么您将得到第一个项目的索引,而不一定是您所在的项目。考虑{ 5, 14, 5,29,…}的数组。当“val”为5时,即使是在第三个元素上,也始终会得到零。在项目中进行foreachKeyValuePair配对,然后引用pair.Key和pair.Value,性能会更好,而不是在每次迭代中进行查找。在值中进行foreachKeyValuePair对,然后引用pair.Key和pair.Value,这将比在每次迭代中进行查找更有效。或者创建一个临时变量,在我记忆中,在每次传递时递增,不能保证foreach将以升序或降序在集合上循环,只能保证它将在每个元素上恰好停止一次,因此,如果使用外部值,则根据实现,您的解决方案可能有效,也可能无效。通常情况下,它会给出所需的结果,但也就是说,一种常见的优化方法是按降序解析数组。与每个周期的升序相比,它所需的机器指令更少。我认为这取决于您迭代的枚举类型。如果它是一个数组,我想顺序是有保证的。
* MoveNext()
* Current
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<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> 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;
    }
public struct IndexValue<T> {
    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<IndexValue<T>> KeyValuePairs<T>(this IList<T> list) {
        for (int i = 0; i < list.Count; i++)
            yield return new IndexValue<T>(i, list[i]);
    }
}
IDictionary<string,string> openWith = new Dictionary<string,string>()
{
   { "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<string,string> de in openWith)
{
    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}