SortedList 泛型类

SortedList 泛型类  
请参见  示例  成员 
 全部折叠 全部展开    语言筛选器: 全部 语言筛选器: 多个 语言筛选器: Visual Basic 语言筛选器: C# 语言筛选器: C
++ 语言筛选器: J# 语言筛选器: JScript  
 Visual Basic(声明) 
 Visual Basic(用法) 
 C# 
 C
++ 
 J# 
 JScript 
注意:此类在 .NET Framework 
2.0 版中是新增的。 

表示键
/值对的集合,这些键/值对基于关联的 IComparer 实现按照键进行排序。 

命名空间:System.Collections.Generic
程序集:System(在 system.dll 中)

语法
Visual Basic(声明) 
<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public Class SortedList(Of TKey, TValue)
    Implements IDictionary(Of TKey, TValue), ICollection(Of KeyValuePair(Of TKey, TValue)), _
    IEnumerable(Of KeyValuePair(Of TKey, TValue)), IDictionary, ICollection, _
    IEnumerable
 
Visual Basic(用法) 
Dim instance As SortedList(Of TKey, TValue)

 
C# 
[SerializableAttribute] 
[ComVisibleAttribute(
false)] 
public class SortedList<TKey,TValue> : IDictionary<TKey,TValue>, ICollection<KeyValuePair<TKey,TValue>>
    IEnumerable
<KeyValuePair<TKey,TValue>>, IDictionary, ICollection, IEnumerable
 
C
++ 
[SerializableAttribute] 
[ComVisibleAttribute(
false)] 
generic
<typename TKey, typename TValue>
public ref class SortedList : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>
    IEnumerable
<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
 
J# 
J# 支持使用泛型类型和方法,但不支持进行新的声明。
 
JScript 
JScript 支持泛型类型和方法。
 


类型参数
TKey 
集合中键的类型。

TValue 
集合中值的类型。

备注
SortedList 泛型类是具有 O(log n) 检索的二进制搜索树,其中 n 是字典中元素的数目。就这一点而言,它与 SortedDictionary 泛型类相似。这两个类具有相似的对象模型,并且都具有 O(log n) 的检索运算复杂度。这两个类的区别在于内存的使用以及插入和移除元素的速度:

SortedList 使用的内存比 SortedDictionary 少。

SortedDictionary 可对未排序的数据执行更快的插入和移除操作,它的运算复杂度为 O(log n),而 SortedList 的运算复杂度为 O(n)。

如果使用排序数据一次性填充列表,则 SortedList 比 SortedDictionary 快。

SortedDictionary 类和 SortedList 类之间的另一个区别是:SortedList 支持通过由 Keys 和 Values 属性返回的集合对键和值执行高效的索引检索。访问此属性时无需重新生成列表,因为列表只是键和值的内部数组的包装。下面的代码演示如何使用 Values 属性从已排序的字符串列表中按索引检索值:

Visual Basic  复制代码 
Dim v As String 
= mySortedList.Values(3)
 
C#  复制代码 
string v = mySortedList.Values[3];
 
C
++  复制代码 
String
^ v = mySortedList->Values[3];
 

SortedList 作为键
/值对的数组来实现,它按键排序。每个元素都可以作为一个 KeyValuePair 对象进行检索。

只要键对象用作 SortedList 中的键,它们就必须是永远不变的。SortedList 中的每个键必须是唯一的。键不能为 空引用(在 Visual Basic 中为 Nothing),但如果列表中值的类型 TValue 为引用类型,则值可以。

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

SortedList 的容量是指 SortedList 可以保存的元素数。在此实现中,SortedList 的默认初始容量为 
16;但此默认值可能在 .NET Framework SDK 的未来版本中更改。当向 SortedList 添加元素后,将通过重新分配内部数组,根据需要自动增大容量。可通过调用 TrimExcess 或通过显式设置 Capacity 属性减少容量。减少容量会重新分配内存并复制 SortedList 中的所有元素。

C# 语言中的 
foreach 语句(在 C++ 中为 for each,在 Visual Basic 中为 For Each)需要集合中的元素类型。由于 SortedList 的元素是键/值对,因此元素类型既不是键的类型,也不是值的类型。而是 KeyValuePair 类型。例如:

C#  复制代码 
foreach (KeyValuePair<intstring> kvp in mySortedList) {}
 
C
++  复制代码 
for each (KeyValuePair<int, String^> kvp in mySortedList) {}
 
Visual Basic  复制代码 
For Each kvp As KeyValuePair(Of Integer, String) In mySortedList
    
Next kvp
 

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

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

此示例使用 Item 属性(C# 中的索引器)检索值,演示了当请求的键不存在时会引发 KeyNotFoundException,以及与键关联的值可以被替换。 

此示例演示如果程序必须经常尝试排序列表中不存在的键值,如何将 TryGetValue 方法作为更有效的值检索方法,以及在调用 Add 方法前,如何使用 ContainsKey 方法测试键是否存在。

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

最后,此示例演示了 Remove 方法。


 
C#  复制代码 
using System;
using System.Collections.Generic;

public class Example
{
    
public static void Main()
    {
        
// Create a new sorted list of strings, with string
        
// keys.
        SortedList<stringstring> openWith = 
            
new SortedList<stringstring>();

        
// Add some elements to the list. There are no 
        
// duplicate keys, but some of the values are duplicates.
        openWith.Add("txt""notepad.exe");
        openWith.Add(
"bmp""paint.exe");
        openWith.Add(
"dib""paint.exe");
        openWith.Add(
"rtf""wordpad.exe");

        
// The Add method throws an exception if the new key is 
        
// already in the list.
        try
        {
            openWith.Add(
"txt""winword.exe");
        }
        
catch (ArgumentException)
        {
            Console.WriteLine(
"An element with Key = \"txt\" already exists.");
        }

        
// The Item property is another name for the indexer, so you 
        
// can omit its name when accessing elements. 
        Console.WriteLine("For key = \"rtf\", value = {0}."
            openWith[
"rtf"]);

        
// The indexer can be used to change the value associated
        
// with a key.
        openWith["rtf"= "winword.exe";
        Console.WriteLine(
"For key = \"rtf\", value = {0}."
            openWith[
"rtf"]);

        
// If a key does not exist, setting the indexer for that key
        
// adds a new key/value pair.
        openWith["doc"= "winword.exe";

        
// The indexer throws an exception if the requested key is
        
// not in the list.
        try
        {
            Console.WriteLine(
"For key = \"tif\", value = {0}."
                openWith[
"tif"]);
        }
        
catch (KeyNotFoundException)
        {
            Console.WriteLine(
"Key = \"tif\" is not found.");
        }

        
// When a program often has to try keys that turn out not to
        
// be in the list, TryGetValue can be a more efficient 
        
// way to retrieve values.
        string value = "";
        
if (openWith.TryGetValue("tif"out value))
        {
            Console.WriteLine(
"For key = \"tif\", value = {0}.", value);
        }
        
else
        {
            Console.WriteLine(
"Key = \"tif\" is not found.");
        }

        
// ContainsKey can be used to test keys before inserting 
        
// them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add(
"ht""hypertrm.exe");
            Console.WriteLine(
"Value added for key = \"ht\": {0}"
                openWith[
"ht"]);
        }

        
// When you use foreach to enumerate list elements,
        
// the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        
foreach( KeyValuePair<stringstring> kvp in openWith )
        {
            Console.WriteLine(
"Key = {0}, Value = {1}"
                kvp.Key, kvp.Value);
        }

        
// To get the values alone, use the Values property.
        IList<string> ilistValues = openWith.Values;

        
// The elements of the list are strongly typed with the 
        
// type that was specified for the SorteList values.
        Console.WriteLine();
        
foreachstring s in ilistValues )
        {
            Console.WriteLine(
"Value = {0}", s);
        }

        
// The Values property is an efficient way to retrieve
        
// values by index.
        Console.WriteLine("\nIndexed retrieval using the Values " +
            
"property: Values[2] = {0}", openWith.Values[2]);

        
// To get the keys alone, use the Keys property.
        IList<string> ilistKeys = openWith.Keys;

        
// The elements of the list are strongly typed with the 
        
// type that was specified for the SortedList keys.
        Console.WriteLine();
        
foreachstring s in ilistKeys )
        {
            Console.WriteLine(
"Key = {0}", s);
        }

        
// The Keys property is an efficient way to retrieve
        
// keys by index.
        Console.WriteLine("\nIndexed retrieval using the Keys " +
            
"property: Keys[2] = {0}", openWith.Keys[2]);

        
// Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove(
"doc");

        
if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine(
"Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Key = rtf, Value = winword.exe
Key = txt, Value = notepad.exe

Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = hypertrm.exe
Value = winword.exe
Value = notepad.exe

Indexed retrieval using the Values property: Values[2] = winword.exe

Key = bmp
Key = dib
Key = doc
Key = ht
Key = rtf
Key = txt

Indexed retrieval using the Keys property: Keys[2] = doc

Remove("doc")
Key "doc" is not found.
 
*/

 

继承层次结构
System.Object 
  System.Collections.Generic.SortedList

线程安全
此类型的公共静态(在 Visual Basic 中为 Shared)成员是线程安全的。但不能保证任何实例成员是线程安全的。

只要不修改该集合,SortedList 就可以同时支持多个阅读器。即便如此,从头到尾对一个集合进行枚举本质上并不是一个线程安全的过程。若要确保枚举过程中的线程安全,可以在整个枚举过程中锁定集合。若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。

平台
Windows 
98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求。

版本信息
.NET Framework
受以下版本支持:
2.0

.NET Compact Framework
受以下版本支持:
2.0



posted @ 2007-03-16 09:27  wenanry  阅读(1276)  评论(0编辑  收藏  举报