Getting the array key in a 'foreach' loop

前端 未结 9 588
别跟我提以往
别跟我提以往 2021-02-03 22:42

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

For example:

PHP

foreach ($array as $key => $value)
{
             


        
9条回答
  •  攒了一身酷
    2021-02-03 23:47

    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.

提交回复
热议问题