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

例如:

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
    }
}
有帮助吗?

解决方案

格劳恩狼的方式 是使用数组执行此操作的最直接、最高效的方法:

使用 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 中的元素。如果这就是您所需要的,那就太过分了,但如果您倾向于进行大量的收集处理,那就很方便了。

其他提示

如果你想抓住关键(阅读: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]);
}

希望有帮助,泰勒

使用 DictionaryEntry 和 KeyValuePair:

基于
微软软件定义网络

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);
}

相关SO问题:KeyValuePair VS DictionaryEntry

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

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

foreach是为了迭代实现IEnumerable的收藏。它通过在集合上调用GetEnumerator来做到这一点,该收藏符将返回枚举器。

该枚举者有一种方法和属性:

* MoveNext()
* Current

电流返回当前枚举的对象,movenext将当前更新到下一个对象。

显然,索引的概念对枚举的概念是陌生的,不能做到。

因此,大多数集合能够使用索引器和for循环结构进行遍历。

与使用本地变量跟踪索引相比,我非常喜欢在这种情况下使用for循环。

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

实际上,如果你想循环遍历数组,你应该使用经典的 for (;;) 循环。但是,使用 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);
}

您可以使用扩展方法自己实现此功能。例如,以下是适用于列表的扩展方法 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]);
    }
}

这是我刚刚针对这个问题想出的解决方案

原始代码:

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;
    }

myKey = Array.IndexOf(values, val);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top