คอลเล็กชันทั่วไปใน C# ได้แก่ ,
รายการ
List
เรามาดูตัวอย่างกัน ในที่นี้ เรามี 6 องค์ประกอบในรายการ −
ตัวอย่าง
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
รายการที่เรียงลำดับคือการรวมกันของอาร์เรย์และตารางแฮช ประกอบด้วยรายการที่สามารถเข้าถึงได้โดยใช้คีย์หรือดัชนี
เรามาดูตัวอย่างกัน ที่นี่ เรามีสี่องค์ประกอบใน 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