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

更新時間: 20-6-2020

573 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

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