SortedList ジェネリック クラスとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > SortedList ジェネリック クラスの意味・解説 

SortedList ジェネリック クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

関連付けられた IComparer 実装基づいてキー並べ替えられた、キー/値ペアコレクション表します

名前空間: System.Collections.Generic
アセンブリ: 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
Dim instance As SortedList(Of
 TKey, TValue)
[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
J# では、ジェネリックな型およびメソッド使用できますが、新規に宣言することはできません。
JScript では、ジェネリックな型およびメソッド使用できません。

型パラメータ

TKey

コレクション内のキーの型。

TValue

コレクション内の値の型。

解説解説

SortedList ジェネリック クラスは、O(log n) 取得使用するバイナリ サーチ ツリーです。n は、ディクショナリ内の要素数を示します。この点で、これは SortedDictionary ジェネリック クラス似てます。この 2 つクラスには、同じようオブジェクト モデルがあり、どちらも O(log n) 取得備えてます。この 2 つクラス違いは、メモリ使用方法と、挿入および削除速度です。

SortedDictionary クラスSortedList クラス違いとして、SortedListキーと値の効率的なインデックスによる取得サポートしていることも挙げられます。これには、Keys プロパティおよび Values プロパティによって返されるコレクション使用されます。リストキーと値の内部配列単なるラッパーなので、プロパティへのアクセス時にリスト再生成する必要はありません。Values プロパティ使用して文字列並べ替えられたリストの値をインデックス取得するコード例次に示します

Dim v As String = mySortedList.Values(3)
string v = mySortedList.Values[3];
String^ v = mySortedList->Values[3];

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 eachVisual Basic の場合For Each) には、コレクション内の要素の型が必要です。SortedList要素キー/値ペアであるため、要素の型は、キーの型や値の型にはなりません。その代わり要素の型は KeyValuePairなります次に例を示します

foreach (KeyValuePair<int, string>
 kvp in mySortedList) {...}
for each (KeyValuePair<int, String^>
 kvp in mySortedList) {...}
For Each kvp As KeyValuePair(Of
 Integer, String) In mySortedList
    ...
Next kvp

foreach ステートメントは、列挙子のラッパーです。これは、コレクションからの読み取りだけを許可しコレクションへの書き込み防ぎます

使用例使用例

文字列キーを含む文字列の空の SortedList作成しAdd メソッド使用していくつかの要素追加するコード例次に示します。この例では、重複するキー追加しようとすると、Add メソッドが ArgumentException をスローすることを示します

この例では、Item プロパティ (C# ではインデクサ) を使用して値を取得し要求されキー存在しないときに KeyNotFoundException がスローされる例を示し、またキー関連付けられた値を置き換えることができること示します

この例では、プログラム並べ替えられたリストにないキー値を頻繁に試行する必要がある場合に、より効率的に値を取得する方法として TryGetValue メソッド使用する方法、および Add メソッド呼び出す前にキー存在するかどうかテストするために ContainsKey メソッド使用する方法示します

この例では、並べ替えられたリストキーと値を列挙する方法、および Keys プロパティValues プロパティ使用してキーと値のみを列挙する方法示します

最後にRemove メソッド使用例示します

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.Object
  System.Collections.Generic.SortedList
スレッド セーフスレッド セーフ

この型の public static (Visual Basic では Shared) メンバは、スレッド セーフです。すべてのインスタンス メンバスレッド セーフになるかどうか保証されていません。

コレクション変更されない限りSortedList では、複数読み込み操作同時に発生して問題ありません。ただし、コレクション列挙処理は、本質的にスレッド セーフな処理ではありません。すべての列挙処理が終わるまでコレクションロックすることにより、列挙処理でのスレッド セーフ確保できますコレクション対し複数スレッドアクセスして読み取り書き込みを行うことができるようにするには、独自に同期化実装する必要があります

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「SortedList ジェネリック クラス」の関連用語

SortedList ジェネリック クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



SortedList ジェネリック クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS