溫馨提示×

c# sorteddictionary如何使用

c#
小樊
121
2024-11-23 01:14:08
欄目: 編程語言

SortedDictionary 是 C# 中的一個類,它是一個字典,其中的元素按照鍵(Key)自動排序。要使用 SortedDictionary,首先需要引用 System.Collections.Generic 命名空間。以下是如何使用 SortedDictionary 的基本步驟:

  1. 創建一個新的 SortedDictionary 實例。
  2. 添加鍵值對到 SortedDictionary 中。
  3. 訪問、修改或刪除 SortedDictionary 中的元素。
  4. 遍歷 SortedDictionary 中的元素。

下面是一個簡單的示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個新的 SortedDictionary 實例
        SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>();

        // 添加鍵值對到 SortedDictionary 中
        sortedDictionary.Add("apple", 3);
        sortedDictionary.Add("banana", 2);
        sortedDictionary.Add("orange", 4);
        sortedDictionary.Add("grape", 1);

        // 訪問 SortedDictionary 中的元素
        Console.WriteLine("SortedDictionary:");
        foreach (KeyValuePair<string, int> item in sortedDictionary)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }

        // 修改 SortedDictionary 中的元素
        sortedDictionary["apple"] = 5;
        Console.WriteLine("\nAfter modifying the value of 'apple':");
        foreach (KeyValuePair<string, int> item in sortedDictionary)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }

        // 刪除 SortedDictionary 中的元素
        sortedDictionary.Remove("banana");
        Console.WriteLine("\nAfter removing 'banana':");
        foreach (KeyValuePair<string, int> item in sortedDictionary)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }
    }
}

輸出:

SortedDictionary:
Key: apple, Value: 3
Key: banana, Value: 2
Key: grape, Value: 1
Key: orange, Value: 4

After modifying the value of 'apple':
Key: apple, Value: 5
Key: banana, Value: 2
Key: grape, Value: 1
Key: orange, Value: 4

After removing 'banana':
Key: apple, Value: 5
Key: grape, Value: 1
Key: orange, Value: 4

在這個示例中,我們創建了一個 SortedDictionary 實例,并向其中添加了一些鍵值對。然后,我們遍歷了 SortedDictionary 中的元素,修改了 “apple” 的值,并刪除了 “banana”。

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