C# 集合系列 :SortedList<TKey,TValue> 类

简述:

命名空间:

System.Collection.Generic

程序集:

System.Collections.dll

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 类型。

表示基于相关的 IComparer<T> 实现按键进行排序的键/值对的集合。

public class SortedList<TKey,TValue> : 
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, 
System.Collections.Generic.IDictionary<TKey,TValue>, 
System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, 
System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, 
System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, 
System.Collections.IDictionary

类型参数:

TKey:

集合中的键的类型。

TValue

集合中值的类型。

实例: 

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // 使用字符串创建新的字符串排序列表
        // keys.
        SortedList<string, string> openWith =
            new SortedList<string, string>();

        // 在列表中添加一些元素。没有重复的键,但有些值是重复的。
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // 如果新密钥已在列表中,则添加方法会抛出一个例外。
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }

        //项目属性是索引器的另一个名称,因此您可以在访问元素时省略其名称。

        Console.WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // 索引器可用于更改与密钥相关的值。

        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // 如果不存在密钥,则为该密钥设置索引器将添加新的密钥/值对。

        openWith["doc"] = "winword.exe";

        // 如果请求的密钥不在列表中,索引器会抛出一个例外。
  
        try
        {
            Console.WriteLine("For key = \"tif\", value = {0}.",
                openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // 当程序经常必须尝试未在列表中的密钥时,TryGetValue 可以是检索值的更有效方法。
  
        string value = "";
        if (openWith.TryGetValue("tif", out value))
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // 包含键可用于在插入密钥之前测试密钥。
        
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}",
                openWith["ht"]);
        }

        // 当您使用前食来列举列表元素时,元素会被检索为关键值Pair对象。
        
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}",
                kvp.Key, kvp.Value);
        }

        // 要单独获取值,请使用值属性。
        IList<string> ilistValues = openWith.Values;

        // 列表的元素强烈地键入为排序列表值指定的类型。
        
        Console.WriteLine();
        foreach( string s in ilistValues )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // 值属性是按索引检索值的有效方法。
        
        Console.WriteLine("\nIndexed retrieval using the Values " +
            "property: Values[2] = {0}", openWith.Values[2]);

        // 要单独获取密钥,请使用钥匙属性。
        IList<string> ilistKeys = openWith.Keys;

        // 列表的元素强烈地键入为排序列表密钥指定的类型。
        
        Console.WriteLine();
        foreach( string s in ilistKeys )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // 按索引检索密钥的钥匙属性是一种有效的方法。
        
        Console.WriteLine("\nIndexed retrieval using the Keys " +
            "property: Keys[2] = {0}", openWith.Keys[2]);

        // 使用"删除"方法删除键/值对。
        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.
 */

构造函数:

SortedList<TKey,TValue>()初始化 SortedList<TKey,TValue> 类的新实例,该示例为空且具有默认的初始容量,并使用默认的 IComparer<T>
SortedList<TKey,TValue>(IComparer<TKey>)初始化 SortedList<TKey,TValue> 类的新实例,该实例为空,具有默认的初始容量并使用指定的 IComparer<T>
SortedList<TKey,TValue>(IDictionary<TKey,TValue>)初始化 SortedList<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素,其容量足以容纳所复制的元素数并使用默认的 IComparer<T>
SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>)初始化 SortedList<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素,其容量足以容纳所复制的元素数并使用指定的 IComparer<T>
SortedList<TKey,TValue>(Int32)初始化 SortedList<TKey,TValue> 类的新实例,该示例为空且具有指定的初始容量,并使用默认的 IComparer<T>
SortedList<TKey,TValue>(Int32, IComparer<TKey>)初始化 SortedList<TKey,TValue> 类的新实例,该实例为空,具有指定的初始容量并使用指定的 IComparer<T>

 属性:

Capacity

获取或设置 SortedList<TKey,TValue> 可包含的元素数。

Comparer

获取该排序列表的 IComparer<T>

Count

获取包含在 SortedList<TKey,TValue> 中的键/值对的数目。

Item[TKey]

获取或设置与指定的键关联的值。

Keys

获取一个按排序顺序包含 SortedList<TKey,TValue> 中的键的集合。

Values

获得一个包含 SortedList<TKey,TValue> 中的值的集合。

方法: 

Add(TKey, TValue)

将带有指定键和值的元素添加到 SortedList<TKey,TValue> 中。

Clear()

从 SortedList<TKey,TValue> 中移除所有元素。

ContainsKey(TKey)

确定 SortedList<TKey,TValue> 是否包含特定键。

ContainsValue(TValue)

确定 SortedList<TKey,TValue> 是否包含特定值。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetEnumerator()

返回循环访问 SortedList<TKey,TValue> 的枚举数。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
IndexOfKey(TKey)

在整个 SortedList<TKey,TValue> 中搜索指定键并返回从零开始的索引。

IndexOfValue(TValue)

在整个 SortedList<TKey,TValue> 中搜索指定的值,并返回第一个匹配项的从零开始的索引。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
Remove(TKey)

从 SortedList<TKey,TValue> 中移除带有指定键的元素。

RemoveAt(Int32)

移除 SortedList<TKey,TValue> 的指定索引处的元素。

ToString()

返回表示当前对象的字符串。

(继承自 Object)
TrimExcess()

如果元素数小于当前容量的 90%,将容量设置为 SortedList<TKey,TValue> 中的实际元素数。

TryGetValue(TKey, TValue)

获取与指定键关联的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值