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.