1 di 1 hanno valutato il contenuto utile: - Valuta questo argomento

LinkedList (classe generica)

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

Rappresenta un elenco a doppio collegamento.

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

[SerializableAttribute] 
[ComVisibleAttribute(false)] 
public class LinkedList<T> : ICollection<T>, IEnumerable<T>, 
	ICollection, IEnumerable, ISerializable, IDeserializationCallback
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

T

Specifica il tipo di elemento dell'elenco collegato.

L'oggetto LinkedList è un elenco collegato di carattere generale. Inoltre, tale oggetto supporta gli enumeratori e implementa l'interfaccia ICollection, in modo coerente con le altre classi dell'insieme di .NET Framework.

L'oggetto LinkedList è di fatto un elenco collegato con nodi separati di tipo LinkedListNode; di conseguenza, l'inserimento e la rimozione sono operazioni O(1). Gli elenchi che contengono tipi di riferimento offrono prestazioni migliori se un nodo e il suo valore vengono creati contemporaneamente. I nodi sottostanti sono esposti ed è pertanto possibile rimuoverli e inserirli nuovamente, nello stesso elenco o in un altro, mediante un'operazione O(1) senza allocazioni sull'heap GC. L'elenco gestisce inoltre un conteggio interno in modo che l'ottenimento della proprietà Count sia un'operazione O(1); il conteggio rimane coerente se l'elenco è utilizzato da un singolo thread.

La classe LinkedList non supporta concatenamenti, suddivisioni, cicli o altre funzionalità che possono rendere incoerente lo stato dell'elenco. Tale classe è infatti progettata per conservare l'integrità dell'elenco e le operazioni su un singolo thread non rendono incoerente l'elenco. L'unico scenario multithreading supportato dalla classe LinkedList sono le operazioni di lettura con multithreading. Negli altri scenari multithreading, è necessario fornire una sincronizzazione personalizzata.

NotaNota

È sempre possibile creare elenchi collegati che garantiscano migliori prestazioni in circostanze specifiche o che consentano di aggiungere nuove funzionalità in cambio di una peggiore sicurezza di programmazione.

Ogni nodo dell'oggetto LinkedList è di tipo LinkedListNode. Dato che la classe LinkedList rappresenta un elenco a doppio collegamento, ogni nodo punta in avanti verso il nodo successivo (indicato dalla proprietà Next) e all'indietro verso il nodo precedente (indicato dalla proprietà Previous). I nodi sono collegati all'elenco in modo tale che le operazioni non valide sull'elenco (come ad esempio il tentativo di rimuovere un nodo che in realtà si trova in un altro elenco) non rendano incoerente lo stato dell'elenco.

L'oggetto LinkedList accetta riferimento null (Nothing in Visual Basic) come proprietà Value valida per i tipi di riferimento e consente valori duplicati.

Se l'oggetto LinkedList è vuoto, le proprietà First e Last contengono riferimento null (Nothing in Visual Basic).

Nell'esempio di codice riportato di seguito vengono illustrate molte funzionalità della classe LinkedList. Nell'esempio viene creata una matrice di stringhe, quindi viene creata e compilata una classe LinkedList di stringhe passando la matrice di stringhe al costruttore LinkedList(IEnumerable generico).

L'elenco collegato risultante viene modificato utilizzando le proprietà e i metodi della classe LinkedList e vengono visualizzati i risultati tra le operazioni.

using System;
using System.Text;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] words = 
            {"the", "fox", "jumped", "over", "the", "dog"};
        LinkedList<string> sentence = new LinkedList<string>(words);
        Display(sentence);

        Console.WriteLine("sentence.Contains(\"jumped\") = {0}", 
            sentence.Contains("jumped"));

        // Add the word "today" to the beginning of the linked list.
        // Remove the new node, and add it to the end of the list.
        sentence.AddFirst("today");
        Display(sentence);

        LinkedListNode<string> mark1 = sentence.First;
        sentence.RemoveFirst();
        sentence.AddLast(mark1);
        Display(sentence);

        sentence.RemoveLast();
        sentence.AddLast("yesterday");
        Display(sentence);

        mark1 = sentence.Last;
        sentence.RemoveLast();
        sentence.AddFirst(mark1);
        Display(sentence);

        sentence.RemoveFirst();

        LinkedListNode<string> current = sentence.FindLast("the");
        DisplayNode(current);

        sentence.AddAfter(current, "old");
        sentence.AddAfter(current, "lazy");
        DisplayNode(current);

        current = sentence.Find("fox");
        DisplayNode(current);

        sentence.AddBefore(current, "quick");
        sentence.AddBefore(current, "brown");
        DisplayNode(current);

        // Keep a reference to the current node, "fox", and to the
        // previous node in the list. Use the Find method to locate
        // the node containing the value "dog". Show the position.
        mark1 = current;
        LinkedListNode<string> mark2 = current.Previous;
        current = sentence.Find("dog");
        DisplayNode(current);

        // The AddBefore method throws an InvalidOperationException
        // if you try to add a node that already belongs to a list.
        try
        {
            sentence.AddBefore(current, mark1);
        }
        catch(InvalidOperationException ex)
        {
            Console.WriteLine("Exception message: {0}", ex.Message);
        }

        // Remove the node referred to by mark1, and add it before 
        // the node referred to by current. Show the sentence, 
        // highlighting the position of the node referred to by
        // current.
        sentence.Remove(mark1);
        sentence.AddBefore(current, mark1);
        DisplayNode(current);

        // Remove the node referred to by current. If you try to show
        // its position now, the DisplayNode method prints a message.
        // Add the node after the node referred to by mark2, and 
        // display the sentence, highlighting current.
        sentence.Remove(current);
        DisplayNode(current);
        sentence.AddAfter(mark2, current);
        DisplayNode(current);

        // The Remove method finds and removes the first node that 
        // that has the specified value.
        sentence.Remove("old");
        Display(sentence);

        // When the linked list is cast to ICollection(Of String),
        // the Add method adds a node to the end of the list. 
        sentence.RemoveLast();
        ICollection<string> icoll = sentence;
        icoll.Add("rhinoceros");
        Display(sentence);

        // Create an array with the same number of elements as the
        // linked list.
        Console.WriteLine("\nCopy the list to an array.");
        string[] sArray = new string[sentence.Count];
        sentence.CopyTo(sArray, 0);

        foreach( string s in sArray )
        {
            Console.WriteLine(s);
        }

        // Release all the nodes.
        sentence.Clear();

    }

    private static void Display(LinkedList<string> words)
    {
        foreach( string word in words )
        {
            Console.Write(word + " ");
        }
        Console.WriteLine();
    }
    
    private static void DisplayNode(LinkedListNode<string> node)
    {
        if (node.List==null)
        {
            Console.WriteLine("Node \"{0}\" is not in a list.", 
                node.Value);
            return;
        }

        StringBuilder result = new StringBuilder("(" + node.Value + ")");
        LinkedListNode<string> nodeP = node.Previous;

        while (nodeP != null)
        {
            result.Insert(0, nodeP.Value + " ");
            nodeP = nodeP.Previous;
        }

        node = node.Next;
        while (node != null)
        {
            result.Append(" " + node.Value);
            node = node.Next;
        }

        Console.WriteLine(result);
    }
}

//This code example produces the following output:
//
//the fox jumped over the dog
//sentence.Contains("jumped") = True
//today the fox jumped over the dog
//the fox jumped over the dog today
//the fox jumped over the dog yesterday
//yesterday the fox jumped over the dog
//the fox jumped over (the) dog
//the fox jumped over (the) lazy old dog
//the (fox) jumped over the lazy old dog
//the quick brown (fox) jumped over the lazy old dog
//the quick brown fox jumped over the lazy old (dog)
//Exception message: The LinkedList node belongs a LinkedList.
//the quick brown jumped over the lazy old fox (dog)
//Node "dog" is not in a list.
//the quick brown (dog) jumped over the lazy old fox
//the quick brown dog jumped over the lazy fox
//the quick brown dog jumped over the lazy rhinoceros
//
//Copy the list to an array.
//the
//quick
//brown
//dog
//jumped
//over
//the
//lazy
//rhinoceros

System.Object
  System.Collections.Generic.LinkedList

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 LinkedList 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. Nel raro caso in cui più enumerazioni tentino di ottenere contemporaneamente l'accesso in scrittura, l'insieme deve essere bloccato 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 CE, Windows Millennium Edition, Windows Mobile per Pocket PC, Windows Mobile per Smartphone, 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

.NET Compact Framework

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

Aggiunte alla community

AGGIUNGI
© 2013 Microsoft. Tutti i diritti riservati.