获取在foreach循环数组键 [英] Getting the array key in a foreach loop
问题描述
我试图让当前元素的关键在的foreach 的循环?
例如:
PHP
的foreach($数组$关键=> $值)
{
回波($值被分配给键:$键);
}
我试图在C#中要做到:
INT [] =值{5,14,29,49,99,150,999};的foreach(中值INT VAL)
{
如果(搜索< = VAL和放大器;&安培;!停止)
{
//设定密钥的可变
}
}
<一个href=\"http://stackoverflow.com/questions/60032/getting-the-array-key-in-a-foreach-loop#60035\">Grauenwolf's方法是一个数组这样做的最直接的和高性能的方式:
使用FOR循环或创建在每次通过增加一个临时变量。
块引用>这当然会是这样的:
INT [] =值{5,14,29,49,99,150,999};对于(INT键= 0;密钥LT; values.Length ++键)
如果(搜索&LT; =值[关键]放大器;&安培;!停止)
{
//设定密钥的可变
}使用.NET 3.5,你可以采取一个功能更强大的方法为好,但它是在现场多了几分冗长,可能会依靠一对夫妇的支持功能了解参观在一个IEnumerable的元素。矫枉过正,如果这是你需要它,但方便,如果你倾向于做了很多收集处理的。
I'm trying to get the key of the current element in a foreach loop?
For example:
PHP
foreach($array as $key => $value) { echo("$value is assigned to key: $key"); }
What I'm trying to do in 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:
Either use a for loop or create a temp variable that you increment on each pass.
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 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屋!