在 C# 中,SortedList 是根据键排序的键/值对的集合。 默认情况下,此集合按升序对键/值对进行排序。 它是通用和非通用类型的集合。 通用 SortedListSystem.Collections.Generic 命名空间中定义,而非通用 SortedList 在 System.Collections 命名空间下定义。

例子:

// C# program to illustrate how
// to create a sortedlist
using System;
using System.Collections;

class YIIBAI {

    // Main Method
    static public void Main()
    {

        // Creating a sortedlist
        // Using SortedList class
        SortedList my_Slist = new SortedList();

        // Adding key/value pairs in
        // SortedList using Add() method
        my_Slist.Add(1.02, "Dog");
        my_Slist.Add(1.07, "Cat");
        my_Slist.Add(1.04, "Rat");
        my_Slist.Add(1.01, "Bird");

        foreach(DictionaryEntry pair in my_Slist)
        {
            Console.WriteLine("{0} and {1}", pair.Key, pair.Value);
        }
        Console.WriteLine();
    }
}

运行输出结果如下:

1.01 and Bird
1.02 and Dog
1.04 and Rat
1.07 and Cat

在 C# 中,SortedDictionary是一个通用集合,用于以排序形式存储键/值对,并且对键进行排序。 SortedDictionarySystem.Collection.Generic 命名空间下定义。 它本质上是动态的,排序字典的大小根据需要而增长。

例子:

// C# program to illustrate how
// to create a sorted dictionary
using System;
using System.Collections.Generic;

class Yiibai {

    // Main Method
    static public void Main()
    {

        // Creating sorted dictionary
        // Using SortedDictionary class
        SortedDictionary<int, string> My_sdict =
            new SortedDictionary<int, string>();

        // Adding key/value pair in Sorted
        // Dictionary Using Add() method
        My_sdict.Add(004, "Roscosmos");
        My_sdict.Add(003, "ESA");
        My_sdict.Add(001, "NASA");
        My_sdict.Add(005, "ISRO");
        My_sdict.Add(002, "CNSA");
        Console.WriteLine("Top 5 space agencies 2025:");

        // Accessing the key/value pair of the
        // SortedDictionary Using foreach loop
        foreach(KeyValuePair<int, string> pair in My_sdict)
        {
            Console.WriteLine("Rank: {0} and Name: {1}", pair.Key, pair.Value);
        }
    }
}

运行结果如下:

Top 5 space agencies 2025:
Rank: 1 and Name: NASA
Rank: 2 and Name: CNSA
Rank: 3 and Name: ESA
Rank: 4 and Name: Roscosmos
Rank: 5 and Name: ISRO

以下是 SortedListSortedDictionary 之间的一些区别:

SortedList SortedDictionary
SortedList 的内存是开销。 SortedDictionary 的内存没有瓶颈。
在 SortedList 中,元素存储在内存中的连续块中。 在 SortedDictionary 中,元素存储在可以分布在整个堆中的单独对象中。
在 SoterdList 中,内存碎片很高。 在 SoterdDictionary 中,内存碎片很少。
它需要更少的内存来存储。 它需要更多的内存来存储。
在 SortedList 中,需要较少的插入和删除操作。 在 SortedDictionary 中,需要更多的插入和删除操作。
在 SortedList 中,可以使用索引访问元素。 在 SortedDictionary 中,可以使用索引或键访问元素。 这里键访问就足够了,不需要使用索引访问元素。
在 SortedList 中,数据已经排好序了。 在 SortedDictionary 中,数据是未排序的形式。