星期三, 8月 27, 2014

[C#] foreach 中的 index

MVA Twenty C# Questions Explained - [12 How do I get the index of the current iteration of a foreach loop?]

簡易範例:利用 for 迴圈取代 foreach
namespace MVATwentyQuestions
{
    class Program
    {
        static void Main(string[] args)
        {
            int curIndex = 0;
            // List
            List<string> stringList = new List<string>();
            stringList.Add("One");
            stringList.Add("Two");
            stringList.Add("Three");
            stringList.Add("Four");
            stringList.Add("Five");
            stringList.Add("Six");
            stringList.Add("Seven");

            for (int i = 0; i < stringList.Count; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}

MVA範例:利用變數在 foreach 中累加
namespace MVATwentyQuestions
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> diction = new Dictionary<string, string>();
            int counter = 0;

            diction.Add("One", "One");
            diction.Add("Two", "Two");
            diction.Add("Three", "Three");
            diction.Add("Four", "Four");
            diction.Add("Five", "Five");
            diction.Add("Six", "Six");
            diction.Add("Seven", "Seven");

           foreach (KeyValuePair<string,string> item in diction)
           {
               Console.WriteLine(counter);
               counter++;    
           }
        }
    }
}
MVA 範例:Collection.Indexof()
namespace MVATwentyQuestions
{
    class Program
    {
        static void Main(string[] args)
        {
            int curIndex = 0;
            // List
            List<string> stringList = new List<string>();
            stringList.Add("One");
            stringList.Add("Two");
            stringList.Add("Three");
            stringList.Add("Four");
            stringList.Add("Five");
            stringList.Add("Six");
            stringList.Add("Seven");

            foreach (string str in stringList)
            {
                curIndex = stringList.IndexOf(str);
                Console.WriteLine(curIndex.ToString());
            }

            // ArraryList
            System.Collections.ArrayList arList = new ArrayList();

            arList.Add("One");
            arList.Add("Two");
            arList.Add("Three");
            arList.Add("Four");
            arList.Add("Five");
            arList.Add("Six");
            arList.Add("Seven");

            foreach (String str in arList)
            {
                curIndex = arList.IndexOf(str);
                Console.WriteLine(curIndex.ToString());
            }
        }
    }
}

沒有留言:

張貼留言