gpt4 book ai didi

c# - 在 'foreach' 循环中获取数组键

转载 作者:IT王子 更新时间:2023-10-29 04:18:32 25 4
gpt4 key购买 nike

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

例如:

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

最佳答案

Grauenwolf's way是使用数组执行此操作的最直接和最有效的方法:

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,您也可以采用更实用的方法,但它在站点上有点冗长,并且可能依赖于一对 support functions对于 visiting IEnumerable 中的元素。如果这就是您所需要的,那就太过分了,但如果您倾向于进行大量收集处理,则非常方便。

关于c# - 在 'foreach' 循环中获取数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com