Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the array key in a 'foreach' loop

Tags:

arrays

c#

How do I get the key of the current element in a foreach loop in C#?

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     } } 
like image 258
Ross Avatar asked Sep 12 '08 21:09

Ross


People also ask

How do you use key value in foreach?

The foreach looping is the best way to access each key/value pair from an array. array_expr is an array. In every loop the value of the current element of the array is assigned to $value and the internal array pointer is advanced by one and the process continue to reach the last array element. array_expr is an array.

Can you use a foreach loop on an array?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.

How can we store values from foreach loop into an array in PHP?

Declare the $items array outside the loop and use $items[] to add items to the array: $items = array(); foreach($group_membership as $username) { $items[] = $username; } print_r($items);


2 Answers

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.

like image 90
Chris Ammerman Avatar answered Sep 24 '22 10:09

Chris Ammerman


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).

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

like image 35
Tyler Avatar answered Sep 22 '22 10:09

Tyler