C# SortedList类

SortedList类表示按键排序的键值对的集合,可以通过键和索引访问。

排序列表是数组和散列表的组合。 它包含可以使用键或索引访问的项目列表。 如果您使用索引访问项目,它是一个ArrayList,如果使用键访问项目,它是一个Hashtable。项目的集合总是按键值排序。

SortedList类的方法和属性

下表列出了SortedList类的一些常用属性:

属性 描述
Capacity 获取或设置SortedList的容量。
Count 获取SortedList中包含的元素数量。
IsFixedSize 获取一个值,指示SortedList是否具有固定大小。
IsReadOnly 获取一个值,指示SortedList是否为只读。
Item 获取并设置与SortedList中的指定键相关联的值。
Keys 获取SortedList中的键。
Values 获取SortedList中的值。

下表列出了SortedList类的一些常用方法:

序号 方法 描述
1 public virtual void Add(object key, object value); 将具有指定键和值的元素添加到SortedList中。
2 public virtual void Clear(); SortedList中删除所有元素。
3 public virtual bool ContainsKey(object key); 确定SortedList是否包含指定的键。
4 public virtual bool ContainsValue(object value); 确定SortedList是否包含指定值。
5 public virtual object GetByIndex(int index); 获取SortedList的指定索引处的值。
6 public virtual object GetKey(int index); 获取SortedList的指定索引处的键。
7 public virtual IList GetKeyList(); 获取SortedList中的键。
8 public virtual IList GetValueList(); 获取SortedList中的值。
9 public virtual int IndexOfKey(object key); 返回SortedList中指定键从零开始的索引。
10 public virtual int IndexOfValue(object value); 返回SortedList中指定值从零开始第一次出现的索引。
11 public virtual void Remove(object key); SortedList中删除指定键的元素。
12 public virtual void RemoveAt(int index); 删除SortedList指定索引处的元素。
13 public virtual void TrimToSize(); 将容量设置为SortedList中实际的元素数量。

例子

以下示例演示了上述概念的使用:

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList sl = new SortedList();

            sl.Add("001", "Maxsu");
            sl.Add("002", "Alibaba");
            sl.Add("003", "Tencent");
            sl.Add("004", "Google");
            sl.Add("005", "Microsoft");
            sl.Add("006", "Apple");
            sl.Add("007", "Huawei");

            if (sl.ContainsValue("zaixian"))
            {
                Console.WriteLine("This student name is already in the list");
            }
            else
            {
                sl.Add("008", "zaixian");
            }

            // get a collection of the keys. 
            ICollection key = sl.Keys;

            foreach (string k in key)
            {
                Console.WriteLine(k + ": " + sl[k]);
            }
        }
    }
}

当上述代码被编译并执行时,它产生以下结果:

001: Maxsu
002: Alibaba
003: Tencent
004: Google
005: Microsoft
006: Apple
007: Huawei
008: zaixian

上一篇: C#集合 下一篇: C#泛型