表示键/值对的集合,这些键和值按键排序并可按照键和索引访问。
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 允许通过相关联键或通过索引对值进行访问,可提供更大的灵活性。
一。添加删除
1。public virtual void add(object key,object value);
此集合中的索引从零开始。
将带有指定键和值的元素添加到 sortedlist。
通过设置 sortedlist 中不存在的键的值,item 属性也可用于添加新元素。例如:mycollection["mynonexistentkey"] = myvalue。但是,如果指定的键已经存在于 sortedlist 中,则设置 item 属性将改写旧值。相比之下,add 方法不修改现有元素。
dropdownlist3.datasource = slist;
dropdownlist3.datatextfield = "key";
dropdownlist3.datavaluefield = "value";
dropdownlist3.databind();
2。public virtual void remove(object key);
从 sortedlist 中移除带有指定键的元素
如果 sortedlist 不包含带有指定键的元素,则 sortedlist 保持不变。不引发异常
3。public virtual void removeat(int index);
移除 sortedlist 的指定索引处的元素。
dropdownlist3.datasource = slist;
dropdownlist3.datatextfield = "key";
dropdownlist3.datavaluefield = "value";
dropdownlist3.databind();
4。public virtual void clear();
从 sortedlist 中移除所有元素count 设置为零。capacity 保持不变。若要重置 sortedlist 的容量,请调用 trimtosize或直接设置 capacity 属性。截去空 sortedlist 会将 sortedlist 的容量设置为默认容量,而不是零
二。与索引有关的操作
1。public virtual void setbyindex(int index,object value);
替换 sortedlist 中指定索引处的值。
2。public virtual object getbyindex(int index);
获取 sortedlist 的指定索引处的值。index必须小于count,否则出错
3.public virtual int indexofkey(object key);
返回 sortedlist 中指定键的从索引,这是hashtable所没有的,因为hashtable没有有序这个概念,它的排序是内部的
4.public virtual int indexofvalue(object value);
返回指定的值在 sortedlist 中第一个匹配项的索引,这是hashtable所没有的,因为hashtable没有有序这个概念,它的排序是内部的
三。其他
1.public virtual object getkey(int index);
获取 sortedlist 的指定索引处的键,这也是hashtable所不可能有的
2.public virtual ilist getkeylist();
获取 sortedlist 中的键
注:ilist 接口,表示可按照索引单独访问的一组对象,其中有一个item属性,在c#也就就是索引器
3.public virtual ilist getvaluelist();
获取 sortedlist 中的值
4.public virtual bool contains(object key);
确定 sortedlist 是否包含特定键
5.public virtual bool containskey(object key);
确定 sortedlist 是否包含特定键,与contains(object key);完全同
6.public virtual bool containsvalue(object value);
确定 sortedlist 是否包含特定值
上述这三个函数与hashtable完全相同
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论