C# 中什麼是泛型集合?


C# 中的泛型集合包括 <List> 、 <SortedList> 等。

列表

List<T> 是一個泛型集合,而 ArrayList 則是非泛型集合。

我們來看一個示例。此處,列表中包含六個元素 −

示例

 即時演示

using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      // Initializing collections
      List myList = new List() {
         "one",
         "two",
         "three",
         "four",
         "five",
         "six"
      };
      Console.WriteLine(myList.Count);
   }
}

輸出

6

排序列表

排序列表是陣列和雜湊表的組合。它包含一個可使用鍵或索引訪問的專案列表。

我們來看一個示例。此處,SortedList 中包含四個元素 −

示例

 即時演示

using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         SortedList sl = new SortedList();

         sl.Add("001", "Tim");
         sl.Add("002", "Steve");
         sl.Add("003", "Bill");
         sl.Add("004", "Tom");

         if (sl.ContainsValue("Bill")) {
            Console.WriteLine("This name is already in the list");
         } else {
            sl.Add("005", "James");
         }

         ICollection key = sl.Keys;

         foreach (string k in key) {
            Console.WriteLine(k + ": " + sl[k]);
         }
      }
   }
}

輸出

This name is already in the list
001: Tim
002: Steve
003: Bill
004: Tom

更新時間:2020-06-20

574 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.