如何foreach在C#循环中获取当前元素的键?
例如:
foreach ($array as $key => $value)
{
echo("$value is assigned to key: $key");
}
Run Code Online (Sandbox Code Playgroud)
int[] values = { 5, 14, 29, 49, 99, 150, 999 };
foreach (int val in values)
{
if(search <= val && !stop)
{
// Set key to a variable
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*man 23
Grauenwolf的方式是使用数组执行此操作的最直接和最高效的方式:
使用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
}
Run Code Online (Sandbox Code Playgroud)
使用.NET 3.5,您也可以采用更实用的方法,但它在网站上更加冗长,并且可能依赖于几个支持函数来访问 IEnumerable中的元素.如果这就是你所需要的,那就太过分了,但是如果你倾向于进行大量的收集处理,那就太方便了.
Tyl*_*ler 20
如果你想获得密钥(读取:索引),那么你必须使用for循环.如果你真的想拥有一个包含键/值的集合,那么我会考虑使用HashTable或Dictionary(如果你想使用Generics).
Dictionary<int, string> items = new Dictionary<int, string>();
foreach (int key in items.Keys)
{
Console.WriteLine("Key: {0} has value: {1}", key, items[key]);
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助,泰勒
使用DictionaryEntry和KeyValuePair:
基于
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);
}
Run Code Online (Sandbox Code Playgroud)
发布的问题:KeyValuePair VS DictionaryEntry