前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# SortedList类概念和示例

C# SortedList类概念和示例

作者头像
全栈程序员站长
发布2022-07-15 14:21:43
1.5K0
发布2022-07-15 14:21:43
举报

大家好,又见面了,我是全栈君

SortedList 类 [C#]   命名空间: System.Collections

  表示键/值对的集合,这些键和值按键排序并可按照键和索引访问。

  SortedList 是 Hashtable 和 Array 的混合。当使用 Item 索引器属性按照元素的键访问元素时,其行为类似于 Hashtable。当使用 GetByIndex 或 SetByIndex 按照元素的索引访问元素时,其行为类似于 Array。

  SortedList 在内部维护两个数组以将数组存储到列表中;即,一个数组用于键,另一个数组用于相关联的值。每个元素都是一个可作为 DictionaryEntry 对象进行访问的键/值对。键不能为空引用(Visual Basic 中为 Nothing),但值可以。 SortedList 的容量是列表可拥有的元素数。随着向 SortedList 中添加元素,容量通过重新分配按需自动增加。可通过调用 TrimToSize 或通过显式设置 Capacity 属性减少容量。   SortedList 的元素将按照特定的 IComparer 实现(在创建 SortedList 时指定)或按照键本身提供的 IComparable 实现并依据键来进行排序。不论在哪种情况下,SortedList 都不允许重复键。

  索引顺序基于排序顺序。当添加元素时,元素将按正确的排序顺序插入 SortedList,同时索引会相应地进行调整。若移除了元素,索引也会相应地进行调整。因此,当在 SortedList 中添加或移除元素时,特定键/值对的索引可能会更改。 由于要进行排序,所以在 SortedList 上操作比在 Hashtable 上操作要慢。但是,SortedList 允许通过相关联键或通过索引对值进行访问,可提供更大的灵活性。 此集合中的索引从零开始。

   C# 语言中的 foreach 语句(在 Visual Basic 中为 for each)需要集合中每个元素的类型。由于 SortedList 的每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型。而是 DictionaryEntry 类型。

如:

foreach (DictionaryEntry de in list) { Console.WriteLine(“遍历”); Console.WriteLine(“/t键:{0}/t值:{1}”, de.Key, de.Value); }

System.Object System.Collections.Generic.SortedList<TKey, TValue> 命名空间: System.Collections.Generic 程序集: System(在 System.dll 中)

代码语言:javascript
复制
[SerializableAttribute]
[ComVisibleAttribute(false)]
public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable
类型参数

TKey

集合中键的类型。

TValue

集合中值的类型。

SortedList<TKey, TValue> 类型公开以下成员。

SortedList<TKey, TValue> 泛型类是具有 O(log n) 检索的键/值对数组,其中 n 是字典中元素的数目。 就这一点而言,它与 SortedDictionary<TKey, TValue> 泛型类相似。 这两个类具有相似的对象模型,并且都具有 O(log n) 的检索运算复杂度。 这两个类的区别在于内存的使用以及插入和移除元素的速度: SortedList<TKey, TValue> 使用的内存比 SortedDictionary<TKey, TValue> 少。 SortedDictionary<TKey, TValue> 可对未排序的数据执行更快的插入和移除操作,它的运算复杂度为 O(log n),而 SortedList<TKey, TValue> 的运算复杂度为 O(n)。 如果使用排序数据一次性填充列表,则 SortedList<TKey, TValue> 比 SortedDictionary<TKey, TValue> 快。 SortedDictionary<TKey, TValue> 类和 SortedList<TKey, TValue> 类之间的另一个区别是:SortedList<TKey, TValue> 支持通过由 Keys 和 Values 属性返回的集合对键和值执行高效的索引检索。 访问此属性时无需重新生成列表,因为列表只是键和值的内部数组的包装。 下面的代码演示如何使用 Values 属性从已排序的字符串列表中按索引检索值:

代码语言:javascript
复制
string v = mySortedList.Values[3];

SortedList<TKey, TValue> 作为键/值对的数组来实现,它按键排序。 每个元素都可以作为一个 KeyValuePair<TKey, TValue> 对象进行检索。 只要键对象用作 SortedList<TKey, TValue> 中的键,它们就必须是永远不变的。 SortedList<TKey, TValue> 中的每个键必须是唯一的。 键不能为 null,但如果列表中值的类型 TValue 为引用类型,则值可以。

SortedList<TKey, TValue> 需要比较器实现来排序和执行比较。 默认比较器 Comparer<T>.Default 检查键类型 TKey 是否实现 System.IComparable<T> 以及是否使用该实现(如果可用)。 否则,Comparer<T>.Default 将检查键类型 TKey 是否实现 System.IComparable。 如果键类型 TKey 未实现任一接口,则您可以在构造函数重载中指定一个接受 comparer 参数的 System.Collections.Generic.IComparer<T> 实现。

SortedList<TKey, TValue> 的容量是指 SortedList<TKey, TValue> 可以保存的元素数。 当向 SortedList<TKey, TValue> 中添加元素时,将通过重新分配内部数组来根据需要自动增大容量。 可通过调用 TrimExcess 或通过显式设置 Capacity 属性减少容量。 减少容量会重新分配内存并复制 SortedList<TKey, TValue> 中的所有元素。 C# 语言中的 foreach 语句(在 C++ 中为 for each,在 Visual Basic 中为 For Each)需要集合中的元素类型。 由于 SortedList<TKey, TValue> 的元素是键/值对,因此元素类型既不是键的类型,也不是值的类型。 而是 KeyValuePair<TKey, TValue> 类型。 例如:

代码语言:javascript
复制
foreach( KeyValuePair<int, string> kvp in mySortedList )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

foreach 语句是对枚举数的包装,它只允许从集合中读取,不允许写入集合。

下面的代码示例使用字符串键创建一个空的字符串 SortedList<TKey, TValue>,并使用 Add 方法添加一些元素。 此示例演示了当尝试添加重复键时,Add 方法会引发 ArgumentException。

此示例使用 Item 属性(C# 中的索引器)检索值,演示了当请求的键不存在时会引发 KeyNotFoundException,以及与键关联的值可以被替换。 此示例演示如果程序必须经常尝试排序列表中不存在的键值,如何将 TryGetValue 方法作为更有效的值检索方法,以及在调用 Add 方法前,如何使用 ContainsKey 方法测试键是否存在。

此示例演示如何在排序列表中枚举键和值,以及如何使用 Keys 属性和 Values 属性分别枚举键和值。 最后,此示例演示了 Remove 方法。

代码语言:javascript
复制
  1 using System;
  2 using System.Collections.Generic;
  3 
  4 public class Example
  5 {
  6     public static void Main()
  7     {
  8         // Create a new sorted list of strings, with string
  9         // keys.
 10         SortedList<string, string> openWith = 
 11             new SortedList<string, string>();
 12 
 13         // Add some elements to the list. There are no 
 14         // duplicate keys, but some of the values are duplicates.
 15         openWith.Add("txt", "notepad.exe");
 16         openWith.Add("bmp", "paint.exe");
 17         openWith.Add("dib", "paint.exe");
 18         openWith.Add("rtf", "wordpad.exe");
 19 
 20         // The Add method throws an exception if the new key is 
 21         // already in the list.
 22         try
 23         {
 24             openWith.Add("txt", "winword.exe");
 25         }
 26         catch (ArgumentException)
 27         {
 28             Console.WriteLine("An element with Key = \"txt\" already exists.");
 29         }
 30 
 31         // The Item property is another name for the indexer, so you 
 32         // can omit its name when accessing elements. 
 33         Console.WriteLine("For key = \"rtf\", value = {0}.", 
 34             openWith["rtf"]);
 35 
 36         // The indexer can be used to change the value associated
 37         // with a key.
 38         openWith["rtf"] = "winword.exe";
 39         Console.WriteLine("For key = \"rtf\", value = {0}.", 
 40             openWith["rtf"]);
 41 
 42         // If a key does not exist, setting the indexer for that key
 43         // adds a new key/value pair.
 44         openWith["doc"] = "winword.exe";
 45 
 46         // The indexer throws an exception if the requested key is
 47         // not in the list.
 48         try
 49         {
 50             Console.WriteLine("For key = \"tif\", value = {0}.", 
 51                 openWith["tif"]);
 52         }
 53         catch (KeyNotFoundException)
 54         {
 55             Console.WriteLine("Key = \"tif\" is not found.");
 56         }
 57 
 58         // When a program often has to try keys that turn out not to
 59         // be in the list, TryGetValue can be a more efficient 
 60         // way to retrieve values.
 61         string value = "";
 62         if (openWith.TryGetValue("tif", out value))
 63         {
 64             Console.WriteLine("For key = \"tif\", value = {0}.", value);
 65         }
 66         else
 67         {
 68             Console.WriteLine("Key = \"tif\" is not found.");
 69         }
 70 
 71         // ContainsKey can be used to test keys before inserting 
 72         // them.
 73         if (!openWith.ContainsKey("ht"))
 74         {
 75             openWith.Add("ht", "hypertrm.exe");
 76             Console.WriteLine("Value added for key = \"ht\": {0}", 
 77                 openWith["ht"]);
 78         }
 79 
 80         // When you use foreach to enumerate list elements,
 81         // the elements are retrieved as KeyValuePair objects.
 82         Console.WriteLine();
 83         foreach( KeyValuePair<string, string> kvp in openWith )
 84         {
 85             Console.WriteLine("Key = {0}, Value = {1}", 
 86                 kvp.Key, kvp.Value);
 87         }
 88 
 89         // To get the values alone, use the Values property.
 90         IList<string> ilistValues = openWith.Values;
 91 
 92         // The elements of the list are strongly typed with the 
 93         // type that was specified for the SorteList values.
 94         Console.WriteLine();
 95         foreach( string s in ilistValues )
 96         {
 97             Console.WriteLine("Value = {0}", s);
 98         }
 99 
100         // The Values property is an efficient way to retrieve
101         // values by index.
102         Console.WriteLine("\nIndexed retrieval using the Values " +
103             "property: Values[2] = {0}", openWith.Values[2]);
104 
105         // To get the keys alone, use the Keys property.
106         IList<string> ilistKeys = openWith.Keys;
107 
108         // The elements of the list are strongly typed with the 
109         // type that was specified for the SortedList keys.
110         Console.WriteLine();
111         foreach( string s in ilistKeys )
112         {
113             Console.WriteLine("Key = {0}", s);
114         }
115 
116         // The Keys property is an efficient way to retrieve
117         // keys by index.
118         Console.WriteLine("\nIndexed retrieval using the Keys " +
119             "property: Keys[2] = {0}", openWith.Keys[2]);
120 
121         // Use the Remove method to remove a key/value pair.
122         Console.WriteLine("\nRemove(\"doc\")");
123         openWith.Remove("doc");
124 
125         if (!openWith.ContainsKey("doc"))
126         {
127             Console.WriteLine("Key \"doc\" is not found.");
128         }
129     }
130 }
131  // http://www.cnblogs.com/roucheng/
132 /* This code example produces the following output:
133 
134 An element with Key = "txt" already exists.
135 For key = "rtf", value = wordpad.exe.
136 For key = "rtf", value = winword.exe.
137 Key = "tif" is not found.
138 Key = "tif" is not found.
139 Value added for key = "ht": hypertrm.exe
140 
141 Key = bmp, Value = paint.exe
142 Key = dib, Value = paint.exe
143 Key = doc, Value = winword.exe
144 Key = ht, Value = hypertrm.exe
145 Key = rtf, Value = winword.exe
146 Key = txt, Value = notepad.exe
147 
148 Value = paint.exe
149 Value = paint.exe
150 Value = winword.exe
151 Value = hypertrm.exe
152 Value = winword.exe
153 Value = notepad.exe
154 
155 Indexed retrieval using the Values property: Values[2] = winword.exe
156 
157 Key = bmp
158 Key = dib
159 Key = doc
160 Key = ht
161 Key = rtf
162 Key = txt
163 
164 Indexed retrieval using the Keys property: Keys[2] = doc
165 
166 Remove("doc")
167 Key "doc" is not found.
168  */

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/120725.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年12月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 类型参数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档