คอลเล็กชัน I/O ตามคีย์ใน C# คือสิ่งที่เราเรียกว่า SortedList -
SortedList<TKey,TValue>
คลาส SortedList แสดงถึงคอลเล็กชันของคู่คีย์และค่าที่จัดเรียงตามคีย์และสามารถเข้าถึงได้ตามคีย์และตามดัชนี นี่คือวิธีที่ทั้งคู่ถูกเพิ่มใน SortedList -
s.Add("Sub1", "Physics");
s.Add("Sub2", "Chemistry");
s.Add("Sub3", "Biology");
s.Add("Sub4", "Java"); ต่อไปนี้คือตัวอย่างที่แสดงคีย์และค่าต่างๆ ใน SortedList −
ตัวอย่าง
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
SortedList s = new SortedList();
s.Add("Sub1", "Economics");
s.Add("Sub2", "Accountancy");
s.Add("Sub3", "Business Studies");
s.Add("Sub4", "English");
Console.WriteLine("Capacity = " + s.Capacity);
// get a collection of the keys.
ICollection key = s.Keys;
foreach (string k in key) {
Console.WriteLine(k + ": " + s[k]);
}
}
}
} ผลลัพธ์
Capacity = 16 Sub1: Economics Sub2: Accountancy Sub3: Business Studies Sub4: English