.NET(C#)如何遍歷Dictionary


我們知道.NET中的Dictionary是鍵/值對的集合,使用起來也是比較方便,Dictionary也可以用KeyValuePair來迭代遍歷,具體如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02DictionaryIterator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("開始遍歷集合");
            IteratorDictionary();
            Console.ReadKey();
        }

        /// <summary>
        /// 遍歷Dictionary集合
        /// </summary>
        private static void IteratorDictionary()
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>
            {
                {"張三", 1},
                {"李四", 2},
                {"王五", 3},
                {"趙六", 4},
                {"田七", 5}
            };

            foreach (KeyValuePair<string, int> keyValuePair in dictionary)
            {
                Console.WriteLine("key:{0}\tvalue:{1}", keyValuePair.Key, keyValuePair.Value);
            }
        }
    }
}

運行結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM