C#中的Pair類


Pair類是KeyValuePair類,它使用C#在一個列表中儲存一對值。

宣告KeyValuePair:

var myList = new List<KeyValuePair>string, int>>();
Now, add some elements:
myList.Add(new KeyValuePair<string, int>("Laptop", 1));
myList.Add(new KeyValuePair<string, int>("Desktop System", 2));
myList.Add(new KeyValuePair<string, int>("Tablet", 3));
myList.Add(new KeyValuePair<string, int>("Mobile", 4));
myList.Add(new KeyValuePair<string, int>("E-Book Reader", 5));
myList.Add(new KeyValuePair<string, int>("LED", 6));

如下所示顯示KeyValuePair:

示例

 線上演示

using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      var myList = new List<KeyValuePair<string, int>>();
      // adding elements
      myList.Add(new KeyValuePair <string, int>("Laptop", 1));
      myList.Add(new KeyValuePair <string, int>("Desktop System", 2));
      myList.Add(new KeyValuePair <string, int>("Tablet", 3));
      myList.Add(new KeyValuePair <string, int>("Mobile", 4));
      myList.Add(new KeyValuePair <string, int>("E-Book Reader", 5));
      myList.Add(new KeyValuePair <string, int>("LED", 6));

      foreach (var val in myList) {
         Console.WriteLine(val);
      }
   }
}

輸出

[Laptop, 1]
[Desktop System, 2]
[Tablet, 3]
[Mobile, 4]
[E-Book Reader, 5]
[LED, 6]

更新於:2020年6月22日

5000+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.