在C#中, SortedList是键/值对的集合,这些键/值对是根据键排序的。默认情况下,此集合以升序对键/值对进行排序。它具有通用和非通用的集合类型。通用SortedList是在System.Collections.Generic命名空间中定义的,而非通用SortedList是在System.Collections命名空间中定义的。
例子:
// C# program to illustrate how
// to create a sortedlist
using System;
using System.Collections;
class GFG {
// 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是一个通用集合,用于以排序形式存储键/值对,并对键进行排序。 SortedDictionary在System.Collection.Generic命名空间下定义。它本质上是动态的,这意味着已排序字典的大小会根据需要而增加。
例子:
// C# program to illustrate how
// to create a sorted dictionary
using System;
using System.Collections.Generic;
class GFG {
// Main Method
static public void Main()
{
// Creating sorted dictionary
// Using SortedDictionary class
SortedDictionary My_sdict =
new SortedDictionary();
// 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 2018:");
// Accessing the key/value pair of the
// SortedDictionary Using foreach loop
foreach(KeyValuePair pair in My_sdict)
{
Console.WriteLine("Rank: {0} and Name: {1}",
pair.Key, pair.Value);
}
}
}
输出:
Top 5 space agencies 2018:
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
以下是SortedList和SortedDictionary之间的一些区别:
SortedList | SortedDictionary |
---|---|
The memory of SortedList is an overhead. | The memory of SortedDictionary is not bottlenecked. |
In SortedList, the elements are stored in a continuous block in memory. | In SortedDictionary, the elements are stored in separate object that can spread all over the heap. |
In SoterdList, the memory fragmentation is high. | In SoterdDictionary, the memory fragmentation is low. |
It require less memory for storage. | It require more memory for storage. |
In SortedList, less inserts and delete operations are required. | In SortedDictionary, more inserts and delete operations are required. |
In SortedList, you can access elements using the index. | In SortedDictionary, you can access elements using index or key. Here key access is sufficient there is no need of accessing elements using index. |
In SortedList, data are already in sorted form. | In SortedDictionary, data are in un-sorted form. |