Foreach循环输出索引值

循环输邮索引值,使用for是没有任何问题:

 

 class Bh
    {
        public string[] str { get; set; }

        public void TestFor()
        {
            for (int i = 0; i < str.Length; i++)
            {
                Console.WriteLine("index:{0},Value:{1}", i, str[i]);
            }
        }
    }
Source Code

 

运行程序:

 

但是,某一情况之下,你在程序中,是使用foreach方法进行循环的,但又想输出索引的话,那怎样实现呢?

 

class Bh
    {
        public string[] str { get; set; }

        public void TestFor()
        {
            for (int i = 0; i < str.Length; i++)
            {
                Console.WriteLine("index:{0},Value:{1}", i, str[i]);
            }
        }

        public void TestForeach()
        {
            int idx = 0;
            foreach (string s in str)
            {
                Console.WriteLine("index:{0},Value:{1}", idx, s);
                idx++;
            }
        }
    }
Source Code


再次运行,结果可见:

 

posted @ 2017-12-27 10:13  Insus.NET  阅读(2517)  评论(0编辑  收藏  举报