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

Thuộc tính Item của SortedList trong C#

SortedList kết hợp array và hash table. Chứa items truy cập bằng key hoặc index.

Item property get/set value với key cụ thể. Cũng dùng để thêm element mới.

Nếu key không tồn tại: myCollection["myNonexistentKey"] = myValue

Nếu key đã tồn tại: ghi đè key/value mới.

Ví dụ

using System;
using System.Collections;
namespace Demo {
    class Program {
        static void Main(string[] args) {
            SortedList s = new SortedList();
            s.Add("S001", "Jack"); s.Add("S002", "Henry");
            s["S003"] = "Brad"; // dùng Item property thêm mới
            ICollection key = s.Keys;
            foreach (string k in key) Console.WriteLine(k + ": " + s[k]);
        }
    }
}

Kết quả

S001: Jack S002: Henry S003: Brad