LinkedList, classe générique (System.Collections.Generic)

Bibliothèque de classes .NET Framework 
LinkedList, classe générique 

Remarque : cette classe est nouvelle dans le .NET Framework version 2.0.

Représente une liste à lien double.

Espace de noms : System.Collections.Generic
Assembly : System (dans system.dll)

SyntaxeSyntaxe


Visual Basic (Déclaration)
<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public Class LinkedList(Of T)
    Implements ICollection(Of T), IEnumerable(Of T), _
    ICollection, IEnumerable, ISerializable, IDeserializationCallback


Visual Basic (Utilisation)
Dim instance As LinkedList(Of T)


C#
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
public class LinkedList<T> : ICollection<T>, IEnumerable<T>, 
    ICollection, IEnumerable, ISerializable, IDeserializationCallback


C++
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
generic<typename T>
public ref class LinkedList : ICollection<T>, IEnumerable<T>, 
    ICollection, IEnumerable, ISerializable, IDeserializationCallback


J#
J#  prend en charge l'utilisation de types et de méthodes génériques mais pas la déclaration de nouveaux types et de méthodes génériques.


JScript
JScript ne prend pas en charge les types et les méthodes génériques.

Paramètres de type

 
T

Spécifie le type d'élément de la liste liée.

NotesNotes

LinkedList est une liste liée à usage général. Elle prend en charge des énumérateurs et implémente l'interface ICollection, ce qui est cohérent par rapport à d'autres classes de collection du .NET Framework.

LinkedList est une liste liée vraie comportant des n?uds séparés de type LinkedListNode, donc l'insertion et la suppression sont des opérations O(1). Les listes qui contiennent des types référence s'exécutent mieux si un n?ud et sa valeur sont créés en même temps. Étant donné que les n?uds sous-jacents sont exposés, il est possible de supprimer des n?uds et de les réinsérer, soit dans la même liste, soit dans une autre liste comme une opération O(1) sans allocations sur le tas GC. La liste conserve également un compte interne afin que l'obtention de la propriété Count soit une opération O(1) ; le compte reste cohérent si la liste est utilisée à partir d'un thread unique.

La classe LinkedList ne prend pas en charge le chaînage, le fractionnement, les cycles ou d'autres fonctionnalités qui peuvent laisser la liste dans un état incohérent. La conception favorise la maintenance de l'intégrité de la liste, et pour les opérations sur un thread unique, une liste reste cohérente. Les opérations de lecture multithread constituent le seul scénario multithread pris en charge par LinkedList. Dans d'autres scénarios multithreads, vous devez fournir votre propre synchronisation.

RemarqueRemarque

Il est toujours possible de créer des listes liées qui s'exécutent mieux dans des circonstances spécifiques, ou qui échangent la sécurité de la programmation pour des fonctionnalités supplémentaires.

Chaque n?ud de LinkedList est du type LinkedListNode. Comme LinkedList est liée doublement, chaque n?ud pointe en avant sur le n?ud Next et en arrière sur le n?ud Previous. Les n?uds ont des liens vers la liste afin que les opérations non valides dans la liste (par exemple, essayer de supprimer un n?ud qui se trouve en fait dans une autre liste) ne la rendent pas incohérente.

LinkedList accepte référence Null (Nothing en Visual Basic) comme Value valide pour les types référence et autorise les valeurs en double.

Si LinkedList est vide, les propriétés First et Last contiennent la valeur référence Null (Nothing en Visual Basic).

ExempleExemple

L'exemple de code suivant illustre de nombreuses fonctionnalités de la classe LinkedList. L'exemple crée un tableau de chaînes, puis crée et remplit un LinkedList de chaînes en passant le tableau de chaînes au constructeur LinkedList(IEnumerable, générique).

L'exemple de code manipule la liste liée obtenue à l'aide des propriétés et méthodes de la classe LinkedList, en affichant les résultats entre les opérations.



Visual Basic
Imports System
Imports System.Text
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

        Dim words() As String = _
            { "the", "fox", "jumped", "over", "the", "dog" }
        Dim sentence As New LinkedList(Of 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)

        Dim mark1 As LinkedListNode(Of String) = 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()

        Dim current As LinkedListNode(Of String) = _
            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
        Dim mark2 As LinkedListNode(Of String) = 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 ex As InvalidOperationException
            Console.WriteLine("Exception message: {0}", ex.Message)
        End Try

        ' 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()
        Dim icoll As ICollection(Of String) = sentence
        icoll.Add("rhinoceros")
        Display(sentence)

        ' Create an array, specifying a size one less than the size
        ' of the linked list, because Visual Basic allocates one 
        ' more element than you specify.
        Console.WriteLine(vbLf & "Copy the list to an array.")
        Dim sArray(sentence.Count - 1) As String 
        sentence.CopyTo(sArray, 0)

        For Each s As String In sArray
            Console.WriteLine(s)
        Next

        ' Release all the nodes.
        sentence.Clear()

    End Sub

    Private Shared Sub Display(ByVal words As LinkedList(Of String))
        For Each word As String In words
            Console.Write(word & " ")
        Next
        Console.WriteLine()
    End Sub
    
    Private Shared Sub DisplayNode(ByVal node As LinkedListNode(Of String))
        If node.List Is Nothing Then
            Console.WriteLine("Node ""{0}"" is not in a list.", node.Value)
            Return
        End If

        Dim result As New StringBuilder ("(" & node.Value & ")")
        Dim nodeP As LinkedListNode(Of String) = node.Previous

        While nodeP IsNot Nothing
            result.Insert(0, nodeP.Value & " ")
            nodeP = nodeP.Previous
        End While

        node = node.Next
        While node IsNot Nothing
            result.Append(" " & node.Value)
            node = node.Next
        End While

        Console.WriteLine(result)
    End Sub

End Class

'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


C#
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


C++
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::Collections::Generic;

void Display(LinkedList<String^>^ words)
{
    for each( String^ word in words )
    {
        Console::Write(word + " ");
    }
    Console::WriteLine();
};
    
void DisplayNode(LinkedListNode<String^>^ node)
{
    if (node->List == nullptr)
    {
        Console::WriteLine("Node \"{0}\" is not in a list.", 
            node->Value);
        return;
    }

    StringBuilder^ result = gcnew StringBuilder("(" + node->Value + ")");
    LinkedListNode<String^>^ nodeP = node->Previous;

    while (nodeP != nullptr)
    {
        result->Insert(0, nodeP->Value + " ");
        nodeP = nodeP->Previous;
    }

    node = node->Next;
    while (node != nullptr)
    {
        result->Append(" " + node->Value);
        node = node->Next;
    }

    Console::WriteLine(result);
};

void main()
{
    array<String^>^ words = 
        {"the", "fox", "jumped", "over", "the", "dog"};
    LinkedList<String^>^ sentence = 
        gcnew LinkedList<String^>((IEnumerable<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.");
    array<String^>^ sArray = gcnew array<String^>(sentence->Count);
    sentence->CopyTo(sArray, 0);

    for each( String^ s in sArray )
    {
        Console::WriteLine(s);
    }

    // Release all the nodes.
    sentence->Clear();
}

//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
Hiérarchie d'héritageHiérarchie d'héritage
System.Object
  System.Collections.Generic.LinkedList
Sécurité des threadsSécurité des threads

Les membres statiques publics (Shared en Visual Basic) de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

LinkedList peut prendre simultanément en charge plusieurs lecteurs, tant que la collection n'est pas modifiée. Même dans ce cas, l'énumération d'une collection n'est intrinsèquement pas une procédure thread-safe. Dans le cas rare où une énumération traite des accès en écriture, la collection doit être verrouillée pendant l'énumération entière. Pour permettre à plusieurs threads d'accéder en lecture et en écriture à la collection, vous devez implémenter votre propre synchronisation.

Plates-formesPlates-formes

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

Informations de versionInformations de version

.NET Framework

Prise en charge dans : 2.0

.NET Compact Framework

Prise en charge dans : 2.0
Voir aussiVoir aussi

Ces informations proviennent du site de http://msdn2.microsoft.com
Source de cette page : http://msdn2.microsoft.com/fr-fr/library/he2s3bh7.aspx

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

10 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-4563
Document créé le 29/10/06 23:17, dernière modification le Vendredi 17 Juin 2011, 12:11
Source du document imprimé : http://www.gaudry.be/dotnet-rf-he2s3bh7.html Document affiché 8 fois ce mois de Mai.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Navigation (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
1,06 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Réfléchis, décide et agis!

Marc Levy [Extrait de Et si c'était vrai...]
 
l'infobrol
Nous sommes le Jeudi 31 Mai 2012, 12:33, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)