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


再次运行,结果可见:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM