对于foreach (var c in s),在循环中,如何随时知道c是s中的第几个元素,也就是c元素在s中的下标(位置)是几

解决方案 »

  1.   


                int[] arr3 = { 4, 5, 6, 6, 7, 2, 5, 6 };
                int index = 0;
                foreach (var c in arr3)
                    Console.WriteLine(index++);
      

  2.   

    http://discuss.joelonsoftware.com/default.asp?dotnet.12.612943.11A foreach uses the IEnumerator interface, which has a Current property, and MoveNext and Reset methods.  So there's not even the concept of an index in it.  (Also, there's no guarantee what order you're enumerating in.)  You'll need to either do your own counting, or use a for loop instead if the collection can take an index. 
      

  3.   

    虽然可以自己加索引变量...但是需要索引器就不应该用foreach应该用for...
      

  4.   

    1.另弄一个变量计数.
    2.用for改写.
      

  5.   


    不另外定义计数变量index,List<>就没有直接的属性或方法记录循环当前下标吗
      

  6.   

    那自己写个CLASS,
    一个记INDEX,一个记数
      

  7.   


    for(int i=0;i<arr3.count;i++)
    {
    /////你要的索引
    Console.WriteLine(i); 
    }
      

  8.   

    个人感觉foreach的本意就是遍历,而不关心下标如果需要就要自己计数
      

  9.   

    可以用Array.IndexOf()获得位置