SortedList 详解

  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);
            }



 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python sorted函数可以用来对列表进行排序,它接收一个可迭代对象作为参数,返回排序后的新列表。示例如下:myList = [3, 8, 5, 1, 9] sortedList = sorted(myList)# sortedList = [1, 3, 5, 8, 9] ### 回答2: Python中的sorted函数是一个非常有用的函数,它用于对可迭代对象进行排序操作。sorted函数可以接受一个可迭代对象作为参数,并返回一个经过排序的新的列表。 sorted函数的基本用法是sorted(iterable, key=None, reverse=False)。其中,iterable表示要排序的可迭代对象,key表示排序的基准,reverse表示排序的顺序。 如果不指定key参数,则sorted函数将按照默认的排序方式进行排序。默认情况下,sorted函数会将可迭代对象中的元素按照从小到大的顺序进行排序。如果可迭代对象中的元素是字符串,那么按照字母的顺序进行排序。 如果想要按照其他的排序方式进行排序,可以使用key参数。key参数接受一个函数作为参数,这个函数将会在排序时作为排序的依据。例如,如果想要按照元素的长度进行排序,可以将len函数作为key参数传入。 另外,reverse参数可以用来控制排序的顺序。如果reverse=True,那么排序的结果将会按照从大到小的顺序排列。 除了传统的列表排序外,sorted函数还可以对字符串进行排序。当对字符串进行排序时,默认情况下会按照字母的顺序进行排序。如果希望使用其他排序方式,仍然可以使用key参数进行指定。 需要注意的是,sorted函数会返回一个新的排序后的列表,原来的可迭代对象不会被改变。如果需要对原来的列表进行排序,可以使用sort方法。 综上所述,Python的sorted函数是一个用于排序的强大工具,它可以对可迭代对象进行排序,并且可以通过key和reverse参数来控制排序的方式和顺序。它的灵活性和易用性使得它在实际的开发中得到了广泛的应用。 ### 回答3: Python中的sorted函数是一个内置函数,用于对可迭代对象进行排序操作。它接受一个可迭代对象作为参数,并返回一个新的已排序的列表。 sorted函数的基本语法如下: sorted(iterable, key, reverse) 其中,iterable参数是表示可迭代对象的集合,如列表、元组或字符串等。key参数是一个可选的函数,用于指定排序的键。reverse参数是一个可选的布尔值,默认为False,表示升序排列;如果设为True,则表示降序排列。 示例如下: ``` numbers = [5, 2, 8, 1, 7] sorted_numbers = sorted(numbers) print(sorted_numbers) ``` 输出结果为:[1, 2, 5, 7, 8] 在上面的示例中,我们传入了一个列表numbers给sorted函数进行排序。返回结果sorted_numbers是一个新的已排序的列表。 我们也可以指定reverse参数来改变排序的顺序: ``` numbers = [5, 2, 8, 1, 7] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers) ``` 输出结果为:[8, 7, 5, 2, 1] 在这个例子中,我们将reverse参数设为True,使得sorted函数按降序排列。 此外,我们还可以使用key参数来指定一个函数,根据函数的返回值进行排序: ``` fruits = ['apple', 'banana', 'cherry', 'date'] sorted_fruits = sorted(fruits, key=len) print(sorted_fruits) ``` 输出结果为:['date', 'apple', 'cherry', 'banana'] 在这个例子中,我们使用key=len来指定一个函数,表示根据字符串的长度进行排序,从而得到按字符串长度升序排列的结果。 总而言之,Python的sorted函数是一个非常有用的工具,它可以帮助我们对可迭代对象进行排序操作。我们可以根据需要指定排序的顺序和规则,从而得到我们想要的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值