SortedList ジェネリック クラス
アセンブリ: System (system.dll 内)
構文
<SerializableAttribute> _ <ComVisibleAttribute(False)> _ Public Class SortedList(Of TKey, TValue) Implements IDictionary(Of TKey, TValue), ICollection(Of KeyValuePair(Of TKey, TValue)), _ IEnumerable(Of KeyValuePair(Of TKey, TValue)), IDictionary, ICollection, _ IEnumerable
[SerializableAttribute] [ComVisibleAttribute(false)] public class SortedList<TKey,TValue> : IDictionary<TKey,TValue>, ICollection<KeyValuePair<TKey,TValue>>, IEnumerable<KeyValuePair<TKey,TValue>>, IDictionary, ICollection, IEnumerable
[SerializableAttribute] [ComVisibleAttribute(false)] generic<typename TKey, typename TValue> public ref class SortedList : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
SortedList ジェネリック クラスは、O(log n) 取得を使用するバイナリ サーチ ツリーです。n は、ディクショナリ内の要素数を示します。この点で、これは SortedDictionary ジェネリック クラスに似ています。この 2 つのクラスには、同じようなオブジェクト モデルがあり、どちらも O(log n) 取得を備えています。この 2 つのクラスの違いは、メモリの使用方法と、挿入および削除の速度です。
-
SortedDictionary には、並べ替えられていないデータ用の高速な挿入操作および削除操作があります。その計算量は、SortedList が O(n) であるのに対して、O(log n) となります。
-
並べ替えられたデータから一度にすべてのデータを取り込む場合、SortedList の方が SortedDictionary よりも高速です。
SortedDictionary クラスと SortedList クラスの違いとして、SortedList がキーと値の効率的なインデックスによる取得をサポートしていることも挙げられます。これには、Keys プロパティおよび Values プロパティによって返されるコレクションが使用されます。リストはキーと値の内部配列の単なるラッパーなので、プロパティへのアクセス時にリストを再生成する必要はありません。Values プロパティを使用して、文字列の並べ替えられたリストの値をインデックスで取得するコード例を次に示します。
SortedList は、キーで並べ替えられた、キー/値ペアの配列として実装されています。各要素は、KeyValuePair オブジェクトとして取得できます。
キー オブジェクトは、SortedList でキーとして使用されている間は不変であることが必要です。SortedList 内のすべてのキーは一意である必要があります。リストの値の型 TValue が参照型である場合、キーを null 参照 (Visual Basic では Nothing) にすることはできませんが、値を null 参照 (Visual Basic では Nothing) にすることはできます。
SortedList は、並べ替えおよび比較の実行のために比較演算子の実装を必要とします。既定の比較演算子 Comparer.Default は、キーの型 TKey が System.IComparable を実装し、利用可能な場合はその実装を使用するかどうかをチェックします。それ以外の場合は、Comparer.Default によって、キーの型 TKey が System.IComparable を実装するかどうかをチェックします。キーの型 TKey がいずれのインターフェイスも実装しない場合は、comparer パラメータを受け取るコンストラクタ オーバーロードの System.Collections.Generic.IComparer 実装を指定できます。
SortedList の容量は、SortedList が保持できる要素数になります。この実装では、SortedList の既定の初期量は 16 ですが、この既定値は将来の .NET Framework のバージョンで変更される可能性があります。SortedList に要素を追加すると、必要に応じて、内部の配列の再割り当てによって容量が自動的に増加します。容量を減らすには、TrimExcess を呼び出すか、Capacity プロパティを明示的に設定します。容量を減らすと、メモリの再割り当てが行われ、SortedList 内のすべての要素がコピーされます。
C# 言語の foreach ステートメント (C++ の場合は for each、Visual Basic の場合は For Each) には、コレクション内の要素の型が必要です。SortedList の要素はキー/値ペアであるため、要素の型は、キーの型や値の型にはなりません。その代わり、要素の型は KeyValuePair になります。次に例を示します。
foreach ステートメントは、列挙子のラッパーです。これは、コレクションからの読み取りだけを許可し、コレクションへの書き込みを防ぎます。
文字列キーを含む文字列の空の SortedList を作成し、Add メソッドを使用していくつかの要素を追加するコード例を次に示します。この例では、重複するキーを追加しようとすると、Add メソッドが ArgumentException をスローすることを示します。
この例では、Item プロパティ (C# ではインデクサ) を使用して値を取得し、要求されたキーが存在しないときに KeyNotFoundException がスローされる例を示し、またキーに関連付けられた値を置き換えることができることも示します。
この例では、プログラムが並べ替えられたリストにないキー値を頻繁に試行する必要がある場合に、より効率的に値を取得する方法として TryGetValue メソッドを使用する方法、および Add メソッドを呼び出す前にキーが存在するかどうかをテストするために ContainsKey メソッドを使用する方法を示します。
この例では、並べ替えられたリストのキーと値を列挙する方法、および Keys プロパティと Values プロパティを使用してキーと値のみを列挙する方法を示します。
Imports System Imports System.Collections.Generic Public Class Example Public Shared Sub Main() ' Create a new sorted list of strings, with string ' keys. Dim openWith As New SortedList(Of 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 Console.WriteLine("An element with Key = ""txt"" already exists.") End Try ' The Item property is the default property, so you ' can omit its name when accessing elements. Console.WriteLine("For key = ""rtf"", value = {0}.", _ openWith("rtf")) ' The default Item property 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 default Item property ' for that key adds a new key/value pair. openWith("doc") = "winword.exe" ' The default Item property throws an exception if the requested ' key is not in the list. Try Console.WriteLine("For key = ""tif"", value = {0}.", _ openWith("tif")) Catch Console.WriteLine("Key = ""tif"" is not found.") End Try ' 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. Dim value As String = "" If openWith.TryGetValue("tif", value) Then Console.WriteLine("For key = ""tif"", value = {0}.", value) Else Console.WriteLine("Key = ""tif"" is not found.") End If ' ContainsKey can be used to test keys before inserting ' them. If Not openWith.ContainsKey("ht") Then openWith.Add("ht", "hypertrm.exe") Console.WriteLine("Value added for key = ""ht"": {0}", _ openWith("ht")) End If ' When you use foreach to enumerate list elements, ' the elements are retrieved as KeyValuePair objects. Console.WriteLine() For Each kvp As KeyValuePair(Of String, String) In openWith Console.WriteLine("Key = {0}, Value = {1}", _ kvp.Key, kvp.Value) Next kvp ' To get the values alone, use the Values property. Dim ilistValues As IList(Of String) = openWith.Values ' The elements of the list are strongly typed with the ' type that was specified for the SortedList values. Console.WriteLine() For Each s As String In ilistValues Console.WriteLine("Value = {0}", s) Next s ' The Values property is an efficient way to retrieve ' values by index. Console.WriteLine(vbLf & "Indexed retrieval using the " & _ "Values property: Values(2) = {0}", openWith.Values(2)) ' To get the keys alone, use the Keys property. Dim ilistKeys As IList(Of String) = openWith.Keys ' The elements of the list are strongly typed with the ' type that was specified for the SortedList keys. Console.WriteLine() For Each s As String In ilistKeys Console.WriteLine("Key = {0}", s) Next s ' The Keys property is an efficient way to retrieve ' keys by index. Console.WriteLine(vbLf & "Indexed retrieval using the " & _ "Keys property: Keys(2) = {0}", openWith.Keys(2)) ' Use the Remove method to remove a key/value pair. Console.WriteLine(vbLf + "Remove(""doc"")") openWith.Remove("doc") If Not openWith.ContainsKey("doc") Then Console.WriteLine("Key ""doc"" is not found.") End If End Sub End Class ' 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. '
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[2]); // 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[2]); // 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."); } } } /* 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. */
System.Collections.Generic.SortedList
この型の public static (Visual Basic では Shared) メンバは、スレッド セーフです。すべてのインスタンス メンバがスレッド セーフになるかどうかは保証されていません。
コレクションが変更されない限り、SortedList では、複数の読み込み操作が同時に発生しても問題ありません。ただし、コレクションの列挙処理は、本質的にはスレッド セーフな処理ではありません。すべての列挙処理が終わるまでコレクションをロックすることにより、列挙処理でのスレッド セーフを確保できます。コレクションに対し複数のスレッドがアクセスして読み取りや書き込みを行うことができるようにするには、独自に同期化を実装する必要があります。
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
SortedList メンバ
System.Collections.Generic 名前空間
IDictionary ジェネリック インターフェイス
Dictionary ジェネリック クラス
SortedDictionary ジェネリック クラス
KeyValuePair ジェネリック構造体
IComparer ジェネリック インターフェイス
- SortedList ジェネリック クラスのページへのリンク