在"foreach"循环中获取阵列键 [英] Getting the array key in a 'foreach' loop
本文介绍了在"foreach"循环中获取阵列键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C#的foreach
循环中获取当前元素的键?
How do I get the key of the current element in a foreach
loop in C#?
例如:
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's way is the most straightforward and performant way of doing this with an array:
要么使用for循环,要么创建一个在每次通过时递增的临时变量.
Either use a for loop or create a temp variable that you increment on each pass.
当然会是这样的:
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,您还可以采用一种更具功能性的方法,但是该方法在站点上更加冗长,并且可能依赖于几个
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 functions for visiting 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.
这篇关于在"foreach"循环中获取阵列键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文