C# SortedList类概念和示例
SortedList 类 [C#]
命名空间: System.Collections
表示键/值对的集合,这些键和值按键排序并可按照键和索引访问。
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 允许通过相关联键或通过索引对值进行访问,可提供更大的灵活性。
此集合中的索引从零开始。
C# 语言中的 foreach 语句(在 Visual Basic 中为 for each)需要集合中每个元素的类型。由于 SortedList 的每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型。而是 DictionaryEntry 类型。
如:
foreach (DictionaryEntry de in list)
{
Console.WriteLine("遍历");
Console.WriteLine("/t键:{0}/t值:{1}", de.Key, de.Value);
}
System.Object
System.Collections.Generic.SortedList<TKey, TValue>
命名空间: System.Collections.Generic
程序集: System(在 System.dll 中)
[SerializableAttribute]
[ComVisibleAttribute(false)]
public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
IDictionary, ICollection, IEnumerable
类型参数
- TKey
-
集合中键的类型。
- TValue
-
集合中值的类型。
SortedList<TKey, TValue> 类型公开以下成员。
SortedList<TKey, TValue> 泛型类是具有 O(log n) 检索的键/值对数组,其中 n 是字典中元素的数目。 就这一点而言,它与 SortedDictionary<TKey, TValue> 泛型类相似。 这两个类具有相似的对象模型,并且都具有 O(log n) 的检索运算复杂度。 这两个类的区别在于内存的使用以及插入和移除元素的速度:
SortedList<TKey, TValue> 使用的内存比 SortedDictionary<TKey, TValue> 少。
SortedDictionary<TKey, TValue> 可对未排序的数据执行更快的插入和移除操作,它的运算复杂度为 O(log n),而 SortedList<TKey, TValue> 的运算复杂度为 O(n)。
如果使用排序数据一次性填充列表,则 SortedList<TKey, TValue> 比 SortedDictionary<TKey, TValue> 快。
SortedDictionary<TKey, TValue> 类和 SortedList<TKey, TValue> 类之间的另一个区别是:SortedList<TKey, TValue> 支持通过由 Keys 和 Values 属性返回的集合对键和值执行高效的索引检索。 访问此属性时无需重新生成列表,因为列表只是键和值的内部数组的包装。 下面的代码演示如何使用 Values 属性从已排序的字符串列表中按索引检索值:
string v = mySortedList.Values[3];
SortedList<TKey, TValue> 作为键/值对的数组来实现,它按键排序。 每个元素都可以作为一个 KeyValuePair<TKey, TValue> 对象进行检索。
只要键对象用作 SortedList<TKey, TValue> 中的键,它们就必须是永远不变的。 SortedList<TKey, TValue> 中的每个键必须是唯一的。 键不能为 null,但如果列表中值的类型 TValue 为引用类型,则值可以。
SortedList<TKey, TValue> 需要比较器实现来排序和执行比较。 默认比较器 Comparer<T>.Default 检查键类型 TKey 是否实现 System.IComparable<T> 以及是否使用该实现(如果可用)。 否则,Comparer<T>.Default 将检查键类型 TKey 是否实现 System.IComparable。 如果键类型 TKey 未实现任一接口,则您可以在构造函数重载中指定一个接受 comparer 参数的 System.Collections.Generic.IComparer<T> 实现。
SortedList<TKey, TValue> 的容量是指 SortedList<TKey, TValue> 可以保存的元素数。 当向 SortedList<TKey, TValue> 中添加元素时,将通过重新分配内部数组来根据需要自动增大容量。 可通过调用 TrimExcess 或通过显式设置 Capacity 属性减少容量。 减少容量会重新分配内存并复制 SortedList<TKey, TValue> 中的所有元素。
C# 语言中的 foreach 语句(在 C++ 中为 for each,在 Visual Basic 中为 For Each)需要集合中的元素类型。 由于 SortedList<TKey, TValue> 的元素是键/值对,因此元素类型既不是键的类型,也不是值的类型。 而是 KeyValuePair<TKey, TValue> 类型。 例如:
foreach( KeyValuePair<int, string> kvp in mySortedList )
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
} foreach 语句是对枚举数的包装,它只允许从集合中读取,不允许写入集合。
下面的代码示例使用字符串键创建一个空的字符串 SortedList<TKey, TValue>,并使用 Add 方法添加一些元素。 此示例演示了当尝试添加重复键时,Add 方法会引发 ArgumentException。
此示例使用 Item 属性(C# 中的索引器)检索值,演示了当请求的键不存在时会引发 KeyNotFoundException,以及与键关联的值可以被替换。
此示例演示如果程序必须经常尝试排序列表中不存在的键值,如何将 TryGetValue 方法作为更有效的值检索方法,以及在调用 Add 方法前,如何使用 ContainsKey 方法测试键是否存在。
此示例演示如何在排序列表中枚举键和值,以及如何使用 Keys 属性和 Values 属性分别枚举键和值。
最后,此示例演示了 Remove 方法。
using System;
using System.Collections.Generic; public class Example
{
public static void Main()
{
// Create a new sorted list of strings, with string
// keys.
SortedList<string, string> openWith =
new SortedList<string, string>(); // Add some elements to the list. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe"); // The Add method throws an exception if the new key is
// already in the list.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
} // The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]); // The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]); // If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe"; // The indexer throws an exception if the requested key is
// not in the list.
try
{
Console.WriteLine("For key = \"tif\", value = {0}.",
openWith["tif"]);
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key = \"tif\" is not found.");
} // When a program often has to try keys that turn out not to
// be in the list, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"tif\" is not found.");
} // ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
} // When you use foreach to enumerate list elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
} // To get the values alone, use the Values property.
IList<string> ilistValues = openWith.Values; // The elements of the list are strongly typed with the
// type that was specified for the SorteList values.
Console.WriteLine();
foreach( string s in ilistValues )
{
Console.WriteLine("Value = {0}", s);
} // The Values property is an efficient way to retrieve
// values by index.
Console.WriteLine("\nIndexed retrieval using the Values " +
"property: Values[2] = {0}", openWith.Values[]); // To get the keys alone, use the Keys property.
IList<string> ilistKeys = openWith.Keys; // The elements of the list are strongly typed with the
// type that was specified for the SortedList keys.
Console.WriteLine();
foreach( string s in ilistKeys )
{
Console.WriteLine("Key = {0}", s);
} // The Keys property is an efficient way to retrieve
// keys by index.
Console.WriteLine("\nIndexed retrieval using the Keys " +
"property: Keys[2] = {0}", openWith.Keys[]); // Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc"); if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
}
}
// http://www.cnblogs.com/roucheng/
/* This code example produces the following output: An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Key = rtf, Value = winword.exe
Key = txt, Value = notepad.exe Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = hypertrm.exe
Value = winword.exe
Value = notepad.exe Indexed retrieval using the Values property: Values[2] = winword.exe Key = bmp
Key = dib
Key = doc
Key = ht
Key = rtf
Key = txt Indexed retrieval using the Keys property: Keys[2] = doc Remove("doc")
Key "doc" is not found.
*/
http://www.cnblogs.com/roucheng/
C# SortedList类概念和示例的更多相关文章
- C#常用的集合类型(ArrayList类、Stack类、Queue类、Hashtable类、SortedList类)
1.ArrayList类 ArrayList类主要用于对一个数组中的元素进行各种处理.在ArrayList中主要使用Add.Remove.RemoveAt.Insert四个方法对栈进行操作.Add方法 ...
- 数据结构和算法 – 6.构建字典: DictionaryBase 类和 SortedList 类
6.1.DictionaryBase 类的基础方法和属性 大家可以把字典数据结构看成是一种计算机化的词典.要查找的词就是关键字,而词的定义就是值. DictionaryBase 类是一种用作专有字 ...
- C#全能数据库操作类及调用示例
C#全能数据库操作类及调用示例 using System; using System.Data; using System.Data.Common; using System.Configuratio ...
- C语言利用 void 类型指针实现面向对象类概念与抽象。
不使用C++时,很多C语言新手可能认为C语言缺乏了面向对象和抽象性,事实上,C语言通过某种组合方式,可以间接性的实现面对对象和抽象. 不过多态和继承这种实现,就有点小麻烦,但是依然可以实现. 核心: ...
- 构造字典:DictionaryBase类和SortedList类
DictionaryBase 类 msdn对DictionaryBase的文档解释 泛型KeyValuePair类 msdnd对泛型KeyValuePair类的文档解释 SortedList类 RUN ...
- C#中SortedList类的使用
C#中SortedList类 命名空间:System.Collections 程序集:mscorlib(在mscorlib.dll中) 语法:public class SortedList : IDi ...
- C语言利用 void 类型指针实现面向对象类概念与抽象
不使用C++时,很多C语言新手可能认为C语言缺乏了面向对象和抽象性,事实上,C语言通过某种组合方式,可以间接性的实现面对对象和抽象. 不过多态和继承这种实现,就有点小麻烦,但是依然可以实现. 核心: ...
- java入门---对象和类&概念详解&实例
Java作为一种面向对象语言.支持以下基本概念: 多态 继承 封装 抽象 类 对象 实例 方法 重载 这篇文章,我们主要来看下: 对象:对象是类的一个实例(对象不是找个女朋友),有状态 ...
- 实用的WPF Xml的简易读写类以及用法示例
转自:http://www.silverlightchina.net/html/study/WPF/2012/0808/17980.html 最近真是写博客写的不可收拾,今天再来一篇. 因为做一些程序 ...
随机推荐
- 【转帖】自助式BI的崛起:三张图看清商业智能和大数据分析市场趋势
自助式BI的崛起:三张图看清商业智能和大数据分析市场趋势 大数据时代,商业智能和数据分析软件市场正在经历一场巨变,那些强调易用性的,人人都能使用的分析软件正在取代传统复杂的商业智能和分析软件成为市场的 ...
- C#中操作xml文件(插入节点、修改、删除)
已知有一个xml文件(bookstore.xml)如下: <?xml version="1.0" encoding="gb2312"?> <b ...
- 关于BigDecimal的使用
为什么使用BigDecimal 使用BigDecimal首先要注意到float,double是无法支持商业计算的.只能支持工程计算.即误差允许的计算.通常float占用4个字节,32位.double占 ...
- Java 10大精华文章收集001
Java语言与JVM中的Lambda表达式全解 Lambda表达式是自Java SE 5引入泛型以来最重大的Java语言新特性,本文是2012年度最后一期Java Magazine中的一篇文章,它介绍 ...
- Spark和hadoop的关系
1. Spark VSHadoop有哪些异同点? Hadoop:分布式批处理计算,强调批处理,常用于数据挖掘和数据分析. Spark:是一个基于内存计算的开源的集群计算系统,目的是让数据分析更加快速, ...
- WinStore控件之Button、HyperlinkButton、RadioButton、CheckBox、progressBar、ScrollViewer、Slider
1.Button protected override void OnNavigatedTo(NavigationEventArgs e) { /* * Button - 按钮控件,其全部功能是通过其 ...
- SQL数据库对于保存特殊字符的解决办法
数据库的Char.Vachar类型可以兼容汉字,但特殊字符不行,在保存包含有特殊字符的字符串.正文时,会将特殊符号替换成一个”?”号. 例如: “基础教育课程手机报•特刊” == > “基础教育 ...
- cocos2dx在ubuntu下配置声音引擎
声音引擎库和cocos2dx的库是分开的我们要使用的时候不得不重新修改一下makefile,首先我们要找到声音引擎库的位置,在cocos2dx的 根目录下有一个lib文件,看一下是否存在libcoco ...
- 使用 AFNetworking 进行 XML 和 JSON 数据请求
(1)XML 数据请求 使用 AFNetworking 中的 AFHTTPRequestOperation 和 AFXMLParserResponseSerializer,另外结合第三方框架 XMLD ...
- LintCode-- Remove Linked List Elements
Remove all elements from a linked list of integers that have valueval. 样例 Given 1->2->3->3- ...