溫馨提示×

c# sorteddictionary怎樣刪除

c#
小樊
117
2024-11-23 01:18:05
欄目: 編程語言

在C#中,SortedDictionary是一個有序字典,它根據鍵的順序存儲和排序元素。要刪除SortedDictionary中的元素,您可以使用Remove()方法。以下是一個示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        SortedDictionary<int, string> mySortedDictionary = new SortedDictionary<int, string>();

        // 添加元素到SortedDictionary
        mySortedDictionary.Add(3, "three");
        mySortedDictionary.Add(1, "one");
        mySortedDictionary.Add(2, "two");

        Console.WriteLine("Original SortedDictionary:");
        foreach (KeyValuePair<int, string> item in mySortedDictionary)
        {
            Console.WriteLine("{0}: {1}", item.Key, item.Value);
        }

        // 刪除SortedDictionary中的元素
        int keyToRemove = 2;
        if (mySortedDictionary.ContainsKey(keyToRemove))
        {
            mySortedDictionary.Remove(keyToRemove);
            Console.WriteLine($"Element with key {keyToRemove} removed.");
        }
        else
        {
            Console.WriteLine($"Element with key {keyToRemove} not found.");
        }

        Console.WriteLine("\nSortedDictionary after removal:");
        foreach (KeyValuePair<int, string> item in mySortedDictionary)
        {
            Console.WriteLine("{0}: {1}", item.Key, item.Value);
        }
    }
}

在這個示例中,我們首先創建了一個SortedDictionary,并添加了一些元素。然后,我們使用Remove()方法刪除了鍵為2的元素。最后,我們遍歷SortedDictionary并輸出其內容。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女