现在的位置: 首页 > 综合 > 正文

SortedList 详解

2013年06月13日 ⁄ 综合 ⁄ 共 5297字 ⁄ 字号 评论关闭

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

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

索引顺序基于排序顺序。当添加元素时,元素将按正确的排序顺序插入SortedList,同时索引会相应地进行调整。若移除了元素,索引也会相应地进行调整。因此,当在SortedList中添加或移除元素时,特定键/值对的索引可能会更改。

虽然SortedList和Hashtable都是键/值对集合,但SortedList是自动排序的,所以速度没有Hashtable块,但前者支持键和索引的对值的访问,而Hashtable只支持键对值的访问,所以SortedList显得更加灵活。  SortedList和Hashtable一样,可以保存任意类型数据,
SortedList集合中的元素类型是DictionaryEntry,了解这一点对于遍历集合中的元素非常关键。

 

SortedList类的语法定义如下:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class SortedList:IDictionary,ICollection,IEnumerable,ICloneale

其继承了IDictionary,ICollection和IEnumerable接口,具备字典、集合和枚举的一些通用的方法。SortedLIst对象的构造方法有6中,通常使用最简单的方法来构造,代码如下:

SortedList的构造器

构造器函数

注释

SortedList ()

初始化 SortedList 类的新实例,该实例为空、具有默认初始容量并根据
IComparable
接口(此接口由添加到 SortedList 中的每个键实现)进行排序。

SortedList (IDictionary)

初始化 SortedList 类的新实例,该实例包含从指定字典复制的元素、具有与所复制的元素数相同的初始容量并根据由每个键实现的 IComparable 接口排序。

SortedList (Int32)

初始化 SortedList 类的新实例,该实例为空、具有指定的初始容量并根据 IComparable 接口(此接口由添加到 SortedList 中的每个键实现)进行排序。

SortedList mysorted = new SortedList();

 

namespace MySortedList
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个SortedList对象        
            SortedList mySortedList = new SortedList();
            mySortedList.Add("First", "Hello");
            mySortedList.Add("Second", "World");
            mySortedList.Add("Third", "!");
            mySortedList.Add("Four", "{1}quot;);  

            //列举SortedList的属性、键、值
            Console.WriteLine("MySortedList");
            Console.WriteLine("  Count:    {0}", mySortedList.Count);
            Console.WriteLine("  Capacity: {0}", mySortedList.Capacity);
            Console.WriteLine("  Keys and Values:");
            PrintIndexAndKeysAndValues(mySortedList);

            #region SortedList获得键、值列表
            SortedList mySortedList1 = new SortedList();
            mySortedList1.Add(1.3, "fox");
            mySortedList1.Add(1.4, "jumped");
            mySortedList1.Add(1.5, "over");
            mySortedList1.Add(1.2, "brown");
            mySortedList1.Add(1.1, "quick");
            mySortedList1.Add(1.0, "The");
            mySortedList1.Add(1.6, "the");
            mySortedList1.Add(1.8, "dog");
            mySortedList1.Add(1.7, "lazy"); 

            //获得指定索引处的键和值
            int myIndex = 3;
            //     获取 System.Collections.SortedList 对象的指定索引处的键
            Console.WriteLine("The key  at index {0} is {1}.", myIndex, mySortedList1.GetKey(myIndex));
            //     获取 System.Collections.SortedList 对象的指定索引处的值
            Console.WriteLine("The value at index {0} is {1}.", myIndex, mySortedList1.GetByIndex(myIndex));   

            // 获得SortedList中的键列表和值列表       
            IList myKeyList = mySortedList1.GetKeyList();
            IList myValueList = mySortedList1.GetValueList();
            // Prints the keys in the first column and the values in the second column.           
            Console.WriteLine("\t-KEY-\t-VALUE-");
            for (int i = 0; i < mySortedList1.Count; i++) 
                Console.WriteLine("\t{0}\t{1}", myKeyList[i], myValueList[i]);

            #endregion 

            #region 为SortedList中的元素重新赋值 
            // Creates and initializes a new SortedList.   
            SortedList mySortedList2 = new SortedList();
            mySortedList2.Add(2, "two");
            mySortedList2.Add(3, "three"); 
            mySortedList2.Add(1, "one");
            mySortedList2.Add(0, "zero");
            mySortedList2.Add(4, "four");           
            // 打印显示列表的键和值         
            Console.WriteLine("The SortedList contains the following values:");
            PrintIndexAndKeysAndValues(mySortedList2);      
   
            // 获得指定键的索引        
            int myKey = 2;
            Console.WriteLine("The key \"{0}\" is at index {1}.", myKey, mySortedList2.IndexOfKey(myKey));      
            // 获得指定值的索引     
            String myValue = "three";
            Console.WriteLine("The value \"{0}\" is at index {1}.", myValue, mySortedList2.IndexOfValue(myValue));      
            // 重新设置指定索引处的值         
            mySortedList2.SetByIndex(3, "III");   // SetByIndex:替换 System.Collections.SortedList 对象中指定索引处的值
            mySortedList2.SetByIndex(4, "IV");       
            //打印显示列表的键和值       
            Console.WriteLine("After replacing the value at index 3 and index 4,");
            PrintIndexAndKeysAndValues(mySortedList2);      
            #endregion
            Console.ReadKey();
        }

        //打印SortedList中的键和值 
        public static void PrintIndexAndKeysAndValues(SortedList myList)  
        {            
            Console.WriteLine("\t-INDEX-\t-KEY-\t-VALUE-");
            for (int i = 0; i < myList.Count; i++)     
            {           
                Console.WriteLine("\t[{0}]:\t{1}\t{2}", i, myList.GetKey(i), myList.GetByIndex(i));     
            }       
            Console.WriteLine();     
        }
    }
}

程序结果:

 

泛型集合SortedList<TKey,TValue>:

如果需要排好序的表,可以使用SortedList<TKey,TValue>。这个类按照键给元素排序。

下面的例子创建一个有序表,其中键和值都是string类型。默认的构造函数创建了一个空表,再用Add()方法添加两本书。使用重载的构造函数,可以定义有序表的容量,传送执行了IComparer<TKey>接口的对象,用于给有序表中得元素排序。

Add()方法的第一个参数是键(书名),第二个参数是值(ISBN号)。除了使用Add()方法之外,还可以使用索引器将元素添加到有序表中。索引器需要把键作为索引参数。如果键已存在,那么Add()方法就抛出一个ArgumentException类型的异常。如果索引器使用相同的键,就用新值替代旧值。

 

            SortedList<string, string> books = new SortedList<string, string>();
            books.Add(".net 2.0 Wrox Box", "978-0-470-04840-5");
            books.Add("Professional C# 2008", "978-0-472-04840-6");
            books["Java SE Professional"] = "978-0-473-04840-8";
            books["C++ book"] = "978-0-470-04840-0";
            foreach (KeyValuePair<string, string> book in books)
            {
                Console.WriteLine("{0},{1}", book.Key, book.Value);
            }

可以使用foreach语句迭代有序表。枚举器返回的元素是KeyValuePair<TKey,TValue>类型,其中包含了键和值。键可以用Key属性访问,值用Value属性访问。

也可以使用Values和Keys属性访问值和键。Values属性返回IList<TValue>,Keys属性返回IList<TKey>,所以,可以在foreach中使用这些属性:

           foreach (string isbn in books.Values)
            {
                Console.WriteLine(isbn);
            }
            foreach (string title in books.Keys)
            {
                Console.WriteLine(title);
            }

如果不是泛型集合的SortedList,每个元素都是一个可作为 DictionaryEntry对象进行访问的键/值对。 

            SortedList books1 = new SortedList();
            books1.Add(".net 2.0 Wrox Box", "978-0-470-04840-5");
            books1.Add("Professional C# 2008", "978-0-472-04840-6");
            books1["Java SE Professional"] = "978-0-473-04840-8";
            books1["C++ book"] = "978-0-470-04840-0";
            foreach (DictionaryEntry de in books1)
            {
                Console.WriteLine("{0},{1}", de.Key, de.Value);
            }

 

抱歉!评论已关闭.