Questo argomento non è stato ancora valutato - Valuta questo argomento

SortedDictionary (classe generica)

Nota: questa classe è stata introdotta con .NET Framework versione 2.0.

Rappresenta un insieme di coppie chiave/valore organizzate in base alla chiave.

Spazio dei nomi: System.Collections.Generic
Assembly: System (in system.dll)

[SerializableAttribute] 
public class SortedDictionary<TKey,TValue> : IDictionary<TKey,TValue>, ICollection<KeyValuePair<TKey,TValue>>, 
	IEnumerable<KeyValuePair<TKey,TValue>>, IDictionary, ICollection, IEnumerable
J# supporta l'utilizzo di tipi e metodi generici ma non la dichiarazione di nuovi.
JScript non supporta tipi e metodi generici.

Parametri di tipo

TKey

Tipo di chiavi nel dizionario.

TValue

Tipo di valori nel dizionario.

La classe generica SortedDictionary è una struttura di ricerca binaria con recupero a complessità O(log n), in cui n è il numero di elementi del dizionario. In questo senso, è simile alla classe generica SortedList. Le due classi hanno modelli a oggetti simili ed entrambe hanno un recupero a complessità O(log n). Segue un confronto fra le due classi in termini di uso della memoria e di velocità di inserimento e rimozione:

  • SortedList utilizza meno memoria di SortedDictionary.

  • Nella classe SortedDictionary, le operazioni di inserimento e rimozione di dati non ordinati sono più veloci rispetto alla classe SortedList: O(log n) anziché O(n).

  • Tuttavia, se l'elenco viene popolato in un'unica operazione con dati già ordinati, la classe SortedList risulta più veloce della classe SortedDictionary.

È possibile recuperare ogni coppia chiave/valore come struttura KeyValuePair o come oggetto DictionaryEntry tramite l'interfaccia non generica IDictionary.

Le chiavi non devono essere modificate finché sono utilizzate come chiavi nella classe SortedDictionary. È necessario che tutte le chiavi incluse nella classe SortedDictionary siano univoche. Una chiave non può essere riferimento null (Nothing in Visual Basic) a differenza di un valore, se il tipo di valore TValue è un tipo di riferimento.

La classe SortedDictionary richiede l'implementazione di un operatore di confronto per eseguire il confronto fra le chiavi. È possibile specificare un'implementazione dell'interfaccia generica IComparer mediante un costruttore che accetta un parametro comparer; se non viene specificata alcuna implementazione, viene utilizzato l'operatore di confronto generico predefinito Comparer.Default. Se il tipo TKey implementa l'interfaccia generica System.IComparable, l'operatore di confronto predefinito utilizza tale implementazione.

L'istruzione foreach del linguaggio C# (for each in C++, For Each in Visual Basic) richiede il tipo di ogni elemento dell'insieme. Poiché ogni elemento di SortedDictionary è una coppia chiave/valore, il tipo di elemento non è il tipo della chiave né il tipo del valore. Il tipo dell'elemento è invece KeyValuePair. Nel codice riportato di seguito viene illustrata la sintassi C#, C++ e Visual Basic.

foreach (KeyValuePair<int, string> kvp in myDictionary) {...}

L'istruzione foreach è un wrapper per l'enumeratore che consente solo di leggere dall'insieme, non di scrivere in esso.

Nell'esempio di codice riportato di seguito viene creata una classe SortedDictionary vuota di stringhe con chiavi stringa e viene utilizzato il metodo Add per aggiungere alcuni elementi. L'esempio dimostra che il metodo Add genera una classe ArgumentException durante il tentativo di aggiunta di una chiave duplicata.

L'esempio utilizza la proprietà Item (l'indicizzatore in C#) per il recupero dei valori, dimostrando in tal modo che viene generata una classe KeyNotFoundException se non è presente una chiave richiesta e che è possibile sostituire un valore associato alla chiave.

L'esempio mostra come utilizzare il metodo TryGetValue come modo più efficace per il recupero di valori se un programma deve provare valori di chiave non presenti nel dizionario e illustra come utilizzare il metodo ContainsKey per verificare l'esistenza di una chiave prima di chiamare il metodo Add.

L'esempio mostra come enumerare le chiavi e i valori nel dizionario e come enumerare le chiavi e i valori da soli utilizzando la proprietà Keys e la proprietà Values.

Infine viene illustrato il metodo Remove.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys.
        //
        Dictionary<string, string> openWith = 
            new Dictionary<string, string>();

        // Add some elements to the dictionary. 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 dictionary.
        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 dictionary.
        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 dictionary, 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 dictionary 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.
        Dictionary<string, string>.ValueCollection valueColl =
            openWith.Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for dictionary values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        Dictionary<string, string>.KeyCollection keyColl =
            openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // 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 = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe

Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe

Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht

Remove("doc")
Key "doc" is not found.
 */

System.Object
  System.Collections.Generic.SortedDictionary

I membri statici pubblici (Shared in Visual Basic) di questo tipo sono thread-safe. Qualsiasi membro di istanza non ha garanzia di essere thread-safe.

Un oggetto SortedDictionary può supportare più lettori simultaneamente, purché l'insieme non venga modificato. Tuttavia, l'enumerazione di un insieme non è di per sé una procedura thread-safe. Per garantire che l'enumerazione sia thread-safe, è possibile bloccare l'insieme durante l'intera enumerazione. Per consentire l'accesso all'insieme in lettura e scrittura da parte di più thread, è necessario implementare una sincronizzazione personalizzata.

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 non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.

.NET Framework

Supportato in: 2.0
Il documento è risultato utile?
(1500 caratteri rimanenti)

Aggiunte alla community

AGGIUNGI
© 2013 Microsoft. Tutti i diritti riservati.