打印本文 打印本文 关闭窗口 关闭窗口
SortedList-asp.net入门笔记(七)
作者:武汉SEO闵涛  文章来源:敏韬网  点击数1881  更新时间:2009/4/23 10:40:05  文章录入:mintao  责任编辑:mintao

SortedList

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

SortedList最合适对一列健/值对 进行排序,在排序时,是对键进行排序,

 

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 允许通过相关联键或通过索引对值进行访问,可提供更大的

灵活性。

 

一。添加删除

1public virtual void Add(object key,object value);

此集合中的索引从零开始。

将带有指定键和值的元素添加到 SortedList

通过设置 SortedList 中不存在的键的值,Item

属性也可用于添加新元素。例如:myCollection["myNonexistentKey"] = myValue。但是,如

果指定的键已经存在于 SortedList 中,则设置 Item 属性将改写旧值。相比之下,Add 方法

不修改现有元素。

SortedList sList = new SortedList();

sList.Add(1,"d");

sList.Add(2,"c");

sList.Add(3,"b");

sList.Add(4,"a");

//结果为d c b a,所以可知是按键排序,而非值排序

DropDownList3.DataSource = sList;

DropDownList3.DataTextField = "Key";

DropDownList3.DataValueField = "Value";

DropDownList3.DataBind();

 

2public virtual void Remove(object key);

SortedList 中移除带有指定键的元素

如果 SortedList 不包含带有指定键的元素,则 SortedList 保持不变。不引发异常

SortedList sList = new SortedList();

sList.Add(1,"d");

sList.Add(2,"c");

sList.Add(3,"b");

sList.Add(4,"a");

//sList.Remove("b");  错误,是按key删除,而非Value

sList.Remove(3);  //删除了[3,"b"]

DropDownList3.DataSource = sList;

DropDownList3.DataTextField = "Key";

DropDownList3.DataValueField = "Value";

DropDownList3.DataBind();

 

3public virtual void RemoveAt(int index);

[1] [2] [3]  下一页

打印本文 打印本文 关闭窗口 关闭窗口