Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lớp SortedList trong C#


SortedList kết hợp array và hash table. Truy cập bằng key hoặc index. Luôn sorted theo key.

Ví dụ Add key-value

using System;
using System.Collections;
namespace Demo {
    class Program {
        static void Main(string[] args) {
            SortedList s = new SortedList();
            s.Add("S1", "Maths"); s.Add("S2", "Science"); s.Add("S3", "English"); s.Add("S4", "Economics");
        }
    }
}

Ví dụ lấy Keys

using System;
using System.Collections;
namespace Demo {
    class Program {
        static void Main(string[] args) {
            SortedList sl = new SortedList();
            sl.Add("ST0", "One"); sl.Add("ST1", "Two"); sl.Add("ST2", "Three");
            sl.Add("ST3", "Four"); sl.Add("ST4", "Five"); sl.Add("ST5", "Six"); sl.Add("ST6", "Seven");
            ICollection key = sl.Keys;
            foreach (string k in key) Console.WriteLine(k);
        }
    }
}