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

Phương thức SortedDictionary.Add() trong C#

SortedDictionary<TKey, TValue>.Add(TKey key, TValue value) thêm một cặp khóa/giá trị vào từ điển đã sắp xếp. Khóa phải duy nhất.

Cú pháp

public void Add(TKey key, TValue value);

Ví dụ 1: Thêm cặp int-string

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();
        sortedDict.Add(100, "Mobile");
        sortedDict.Add(200, "Laptop");
        sortedDict.Add(300, "Desktop");
        sortedDict.Add(400, "Speakers");
        sortedDict.Add(500, "Headphone");
        sortedDict.Add(600, "Earphone");

        Console.WriteLine("Các cặp khóa-giá trị SortedDictionary...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Khóa = " + demoEnum.Key + ", Giá trị = " + demoEnum.Value);
    }
}

Kết quả

Các cặp khóa-giá trị SortedDictionary...
Khóa = 100, Giá trị = Mobile
Khóa = 200, Giá trị = Laptop
Khóa = 300, Giá trị = Desktop
Khóa = 400, Giá trị = Speakers
Khóa = 500, Giá trị = Headphone
Khóa = 600, Giá trị = Earphone

Ví dụ 2: Thêm cặp string-string và kiểm tra khóa

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();
        sortedDict.Add("A", "John");
        sortedDict.Add("B", "Andy");
        sortedDict.Add("C", "Tim");
        sortedDict.Add("D", "Ryan");
        sortedDict.Add("E", "Kevin");
        sortedDict.Add("F", "Katie");
        sortedDict.Add("G", "Brad");

        Console.WriteLine("Các cặp khóa-giá trị...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Khóa = " + demoEnum.Key + ", Giá trị = " + demoEnum.Value);

        Console.WriteLine("\nSortedDictionary có khóa 'F'? = " + sortedDict.ContainsKey("F"));
    }
}

Kết quả

Các cặp khóa-giá trị...
Khóa = A, Giá trị = John
Khóa = B, Giá trị = Andy
Khóa = C, Giá trị = Tim
Khóa = D, Giá trị = Ryan
Khóa = E, Giá trị = Kevin
Khóa = F, Giá trị = Katie
Khóa = G, Giá trị = Brad
SortedDictionary có khóa 'F'? = True