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

Truy cập phần tử đầu tiên trong Dictionary C#

Dictionary<TKey, TValue> không bảo đảm thứ tự (trước .NET Core 3.0/.NET 5). Tuy nhiên, từ .NET 6+, thứ tự chèn được bảo toàn. Truy cập phần tử đầu bằng key đã biết.

Ví dụ minh họa

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Dictionary<int, string> d = new Dictionary<int, string>()
        {
            {1, "Electronics"},
            {2, "Clothing"},
            {3, "Toys"},
            {4, "Footwear"},
            {5, "Accessories"}
        };

        foreach (KeyValuePair<int, string> ele in d)
            Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);

        Console.WriteLine("Phần tử đầu (Key=1): " + d[1]);
    }
}

Kết quả đầu ra

Key = 1, Value = Electronics
Key = 2, Value = Clothing
Key = 3, Value = Toys
Key = 4, Value = Footwear
Key = 5, Value = Accessories
Phần tử đầu (Key=1): Electronics

Cách an toàn hơn: d.FirstOrDefault().Value (cần using System.Linq) hoặc d.Values.FirstOrDefault() - không phụ thuộc key cụ thể.