C# 程式訪問字典中的第一個元素


以下是包含一些元素的字典 −

Dictionary<int, string> d = new Dictionary<int, string>() {
   {1,"Electronics"},
   {2, "Clothing"},
   {3,"Toys"},
   {4,"Footwear"},
   {5, "Accessories"}
};

現在要顯示第一個元素,請像這樣設定鍵。

d[1];

上述顯示第一個元素。

示例

 現場演示

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      Dictionary<int, string> d = new Dictionary<int, string>() {
         {1,"Electronics"},
         {2, "Clothing"},
         {3,"Toys"},
         {4,"Footwear"},
         {5, "Accessories"}
      };
      foreach (KeyValuePair<int, string> ele in d) {
         Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
      }
      Console.WriteLine("First element: "+d[1]);
   }
}

輸出

Key = 1, Value = Electronics
Key = 2, Value = Clothing
Key = 3, Value = Toys
Key = 4, Value = Footwear
Key = 5, Value = Accessories
First element: Electronics

更新於:2020 年 6 月 23 日

4K+ 瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.