C# 在“foreach”循环中获取数组键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/60032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the array key in a 'foreach' loop
提问by Ross
How do I get the key of the current element in a foreach
loop in C#?
如何foreach
在 C#中的循环中获取当前元素的键?
For example:
例如:
PHP
PHP
foreach ($array as $key => $value)
{
echo("$value is assigned to key: $key");
}
What I'm trying to do in C#:
我在 C# 中尝试做的事情:
int[] values = { 5, 14, 29, 49, 99, 150, 999 };
foreach (int val in values)
{
if(search <= val && !stop)
{
// Set key to a variable
}
}
采纳答案by Chris Ammerman
Grauenwolf's wayis the most straightforward and performant way of doing this with an array:
Grauenwolf 的方法是使用数组执行此操作的最直接和高效的方法:
Either use a for loop or create a temp variable that you increment on each pass.
要么使用 for 循环,要么创建一个在每次传递时递增的临时变量。
Which would of course look like this:
这当然看起来像这样:
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
}
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 support functionsfor visitingthe 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.
在 .NET 3.5 中,您也可以采用更实用的方法,但它在站点上有点冗长,并且可能依赖于一些支持函数来访问IEnumerable 中的元素。如果这就是您所需要的一切,那么就矫枉过正,但如果您倾向于进行大量收集处理,则很方便。
回答by Jonathan Allen
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.
唉,没有内置的方法可以做到这一点。要么使用 for 循环,要么创建一个在每次传递时递增的临时变量。
回答by Billy Jo
myKey = Array.IndexOf(values, val);
myKey = Array.IndexOf(values, val);
回答by Tyler
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).
如果您想获得键(读取:索引),则必须使用 for 循环。如果您确实想要一个包含键/值的集合,那么我会考虑使用 HashTable 或字典(如果您想使用泛型)。
Dictionary<int, string> items = new Dictionary<int, string>();
foreach (int key in items.Keys)
{
Console.WriteLine("Key: {0} has value: {1}", key, items[key]);
}
Hope that helps, Tyler
希望有帮助,泰勒
回答by huseyint
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:
实际上,如果要遍历数组,则应该使用经典 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);
}
回答by FlySwat
I answered this in another version of this question:
我在这个问题的另一个版本中回答了这个问题:
Foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.
This Enumerator has a method and a property:
* MoveNext() * Current
Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.
Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done.
Because of that, most collections are able to be traversed using an indexer and the for loop construct.
I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.
Foreach 用于迭代实现 IEnumerable 的集合。它通过在集合上调用 GetEnumerator 来完成此操作,该集合将返回一个 Enumerator。
这个 Enumerator 有一个方法和一个属性:
* MoveNext() * Current
Current 返回 Enumerator 当前所在的对象,MoveNext 将 Current 更新为下一个对象。
显然,索引的概念与枚举的概念无关,无法做到。
因此,大多数集合都可以使用索引器和 for 循环构造进行遍历。
与使用局部变量跟踪索引相比,我更喜欢在这种情况下使用 for 循环。
How do you get the index of the current iteration of a foreach loop?
回答by mat3
Here's a solution I just came up with for this problem
这是我刚刚为这个问题提出的解决方案
Original code:
原始代码:
int index=0;
foreach (var item in enumerable)
{
blah(item, index); // some code that depends on the index
index++;
}
Updated code
更新代码
enumerable.ForEach((item, index) => blah(item, index));
Extension Method:
扩展方法:
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;
}
回答by Craig Gidney
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:
您可以使用扩展方法自己实现此功能。例如,这是一个适用于列表的扩展方法 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]);
}
}
回答by Guillaume Massé
With DictionaryEntry and KeyValuePair:
使用 DictionaryEntry 和 KeyValuePair:
Based on
MSDN
基于
MSDN
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);
}