[.Net 2.0] - Tour d'horizon des membres des générics - System.Collections.Generic.List

[.NET 2.0] - Tour d horizon des membres des generics - System.Collections.Generic.List

Ce que j'utilise pour les exemples

Code de la Form principale

public ContactCollection oContacts;
private void Form1_Load(object sender, EventArgs e)
{
    oContacts = new ContactCollection();
    oContacts.Add(new Contact(1, "Dupond", "Julien", "jdupond@hotmail.fr"));
    oContacts.Add(new Contact(2, "Martin", "Pierre", "pmartin@hotmail.fr"));
    oContacts.Add(new Contact(3, "Bellin", "Marie", "mb3@yahoo.fr"));
    oContacts.Add(new Contact(4, "Durand", "Paul", "durand1006@voila.fr"));
    oContacts.Add(new Contact(5, "Suisse", "André", "andre05@voila.fr"));
}

Le prédicat employé tout au long des exemples:

private bool StartWith(Contact oContact)
{
    bool bResult = false;

    if (oContact.Name.StartsWith("D"))
    {
        bResult = true;
    }
    else
    {
        bResult = false;
    }
    return bResult;
}

La classe collection ContactCollection (j'mploie ici une classe Collection héritant de System.Collections.Generic.List, mais on peut employer une liste de la même manière)

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

namespace EtudeCollectionsGeneriques
{
    public class ContactCollection : System.Collections.Generic.List<Contact>
    {
    }
}

La classe Contact

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

namespace EtudeCollectionsGeneriques
{
    public class Contact : IComparable<Contact>
    {
        private int _ID;
        private string _Name;
        private string _FirstName;
        private string _Email;

        public Contact()
        {
        }
        public Contact(int ID, string Name, string FirstName, string Email)
        {
            this.ID = ID;
            this.Name = Name;
            this.FirstName = FirstName;
            this.Email = Email;
        }

        public int ID
        {
            get { return _ID; }
            set { _ID = value; }
        }
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }
        public string Email
        {
            get { return _Email; }
            set { _Email = value; }
        }

        public override string ToString()
        {
            return this.ID.ToString() + " " + this.Name + " " + this.FirstName + " " + this.Email;
        }


        public class ContactNameComparer : System.Collections.Generic.IComparer<Contact>
        {
            public SorterMode SorterMode;
            public ContactNameComparer()
            { }
            public ContactNameComparer(SorterMode SorterMode)
            {
                this.SorterMode = SorterMode;
            }
            #region IComparer<Contact> Membres
            int System.Collections.Generic.IComparer<Contact>.Compare(Contact x, Contact y)
            {
                if (SorterMode == SorterMode.Ascending)
                {
                    return y.Name.CompareTo(x.Name);
                }
                else
                {
                    return x.Name.CompareTo(y.Name);
                }
            }
            #endregion
        }

        #region IComparable<Contact> Membres

        public int CompareTo(Contact other)
        {
            return this.ID.CompareTo(other.ID);
        }
        

        #endregion
    }
}

Ajout

Ajouter un élément à la collection

Add()

Permet d'ajouter un élément à la collection

// 1 on crée un objet
Contact oContact;
oContact=new Contact(9,"Leneuf","Jean-pierre","neuf9@hotmail.com");
// 2 on ajoute l objet à la collection
oContacts.Add(oContact);

Variante :

// 1 on crée un objet
Contact oContact;
oContact=new Contact();//
oContact.ID = 9;
oContact.Name = "Leneuf";
oContact.FirstName = "Jean-pierre";
oContact.Email = "neuf9@hotmail.com");
// 2 on ajoute l objet à la collection
oContacts.Add(oContact);

Ou encore plus rapide :

oContacts = new ContactCollection();
oContacts.Add(new Contact(1, "Dupond", "Julien", "jdupond@hotmail.fr"));
oContacts.Add(new Contact(2, "Martin", "Pierre", "pmartin@hotmail.fr"));

Insert()

// insérer un element à l index spécifié
oContacts.Insert(2, new Contact(8, "Perrot", "Alphonse", "aperrot@hotmail.fr"));

Ajout de collection à la collection

AddRange()

Permet d ajouter une collection (de même type) à la collection

// 1 on crée une collection
ContactCollection oRangeContacts;
oRangeContacts = new ContactCollection();
oRangeContacts.Add(new Contact(6, "Cossin", "Luc", "cossinluc@laposte.net"));
oRangeContacts.Add(new Contact(7, "Mars", "Julie", "mars13@hotmail.fr"));
// 2 on ajoute la collection à la collection
oContacts.AddRange(oRangeContacts);

InsertRange()

ContactCollection oRangeContacts;
oRangeContacts = new ContactCollection();
oRangeContacts.Add(new Contact(6, "Cossin", "Luc", "cossinluc@laposte.net"));
oRangeContacts.Add(new Contact(7, "Mars", "Julie", "mars13@hotmail.fr"));
// On insère à la position 2 les nouveaux éléments
oContacts.InsertRange(2, oRangeContacts);

Modification

Modifier un élément de la collection.

Il faut :

1 - trouver / déterminer l'élément à modifier (avec les méthodes Find(),FindLast(),etc.)
2 - appliquer les modifications à l'élément

Soit en accédant à l élément directement

Contact oContact = oContacts.Find(StartWith);
oContact.Name = "Gaston";

Soit en passant par l'index de la collection

oContacts[2].Name = "Gaston";

Suppression

Remove()

1 - déterminer l'élément à supprimer
2 - faire appel à la méthode Remove() de la collection en passant cet élément

oContacts.Remove(oContacts.FindLast(StartWith));

RemoveAt()

Pour supprimer l élément à l index de la collection spécifié

oContacts.RemoveAt(1);

RemoveAll()

Supprimer tous les éléments de la collection en respectant un prédicat

oContacts.RemoveAll(StartWith);

RemoveRange()

Supprimer des éléments de la collection sur une plage

// supprime 3 contacts à partir de l index 2 de la collection de contacts
oContacts.RemoveRange(2, 3);

Clear()

Supprimer tous les éléments de la collection

oContacts.Clear();

Consultation

Boucles for et foreach

foreach (Contact oContact in oContacts)
{

}

for (int nCount = 0; nCount <= oContacts.Count - 1; nCount++)
{

}

GetEnumerator()

string smessage = string.Empty;
IEnumerator<Contact> oContactsEnumerator = oContacts.GetEnumerator();
while (oContactsEnumerator.MoveNext())
{
    smessage += oContactsEnumerator.Current.ToString() + Environment.NewLine;
}

ForEach()

string smessage=string.Empty;
oContacts.ForEach(delegate(Contact oContact)
{
    smessage += oContact.ToString() + Environment.NewLine;
}
MessageBox.Show(smessage);

AsReadOnly()

Pour obtenir la collection mais ne pouvant être que consultée

//AsReadOnly() retourne la collection mais en lecture seule (ici l'édition dans le datagridview sera impossible)
dataGridView1.DataSource = oContacts.AsReadOnly();

GetRange()

Pour extraire des éléments de la collection

// extrait à partir de la position 2 de la collection, 3 éléments (contact)
List<Contact> oRangeContacts = oContacts.GetRange(2, 3);

Chercher/Trouver

Find()

Trouver un élément respectant un prédicat (si plusieurs éléments correspondent au prédicat c'est le premier qui respecte celui-ci qui est renvoyé)

Contact oContact = oContacts.Find(StartWith);
MessageBox.Show(oContact.ToString());

IndexOf ()

Trouver l'index d'un élément.

Contact oContact = oContacts.FindLast(StartWith);
int nIndex = oContacts.IndexOf(oContact);

FindIndex()

Renvoie l'index (int) de la position du premier élément respectant un prédicat.

MessageBox.Show(oContacts.FindIndex(StartWith).ToString());

FindLast()

Trouver le dernier élément respectant un prédicat.

MessageBox.Show(oContacts.FindLast(StartWith).ToString());

LastIndexOf()

Trouver l'index du dernier élément de la collection respectant un prédicat

Contact oContact = oContacts.FindLast(StartWith);
int nIndex = oContacts.LastIndexOf(oContact);

FindLastIndex()

Renvoie l'index (int) du dernier élément de la collection respectant un prédicat

MessageBox.Show(oContacts.FindLastIndex(StartWith).ToString());

FindAll()

Trouver tous les éléments (FindAll() retourne une liste générique) respectant un prédicat

dataGridView1.DataSource = oContacts.FindAll(StartWith);

Trier

1 - Avec l'interface IComparable implémentée par la classe Contact

oContacts.Sort();

2 - Avec l'interface IComparer implémentée par la classe ContactNameComparer (classe imbriquée dans la classe Contact)

oContacts.Sort(new Contact.ContactNameComparer(SorterMode.Ascending));

Si vous ne connaissez pas bien comment trier avec IComparable et IComparer vous pouvez regarder cet article: http://romagny13.over-blog.com/article-6254481.html

Ou encore regarder cette source ;)
http://codes-sources.commentcamarche.net/source/34515-utilisation-de-icomparer

Conversions

CopyTo()

Copier vers un tableau la collection

Contact[] ContactArrray;
ContactArrray = new Contact[5];
oContacts.CopyTo(ContactArrray);

dataGridView1.DataSource = ContactArrray;

ToArray()

Convertir en tableau la collection

Contact[] ContactArrray = oContacts.ToArray();

ConvertAll()

Convertir la collection vers un autre type
Exemple :
Je vais convertir ma liste de contacts vers une liste de personnes

List<Person> ListPerson = oContacts.ConvertAll(new Converter<Contact, Person>(ConvertToPerson));
dataGridView1.DataSource = ListPerson;

La méthode appelée pour effectuer la conversion :

public Person ConvertToPerson(Contact oContact)
{
    return new Person(oContact.ID, oContact.Name, oContact.FirstName, oContact.Email);
}

La classe Person

public class Person
{
    private int _ID;
    private string _Name;
    private string _FirstName;
    private string _Email;

    public Person()
    {
    }
    public Person(int ID, string Name, string FirstName, string Email)
    {
        this.ID = ID;
        this.Name = Name;
        this.FirstName = FirstName;
        this.Email = Email;
    }

    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
    public string FirstName
    {
        get { return _FirstName; }
        set { _FirstName = value; }
    }
    public string Email
    {
        get { return _Email; }
        set { _Email = value; }
    }
}

Autres

Contains()

Savoir si la collection contient un élément

Contact oContact = oContacts.Find(StartWith);
MessageBox.Show(oContacts.Contains(oContact).ToString());

Exists()

Renvoie un Bool indiquant si au moins un element de la collection respecte le prédicat

MessageBox.Show(oContacts.Exists(StartWith).ToString());

TrueForAll()

Renvoie un bool indiquant si tous les éléments de la collection respecte un prédicat

MessageBox.Show(oContacts.TrueForAll(StartWith).ToString());

Equals()

Compare 2 éléments et renvoie un bool

MessageBox.Show(oContacts[1].Equals(oContact).ToString());

GetType()

Renvoie le type de la collection

MessageBox.Show(oContacts.GetType().ToString());

Reverse()

Méthode permettant inverser les éléments de la collection

oContacts.Reverse();

Count

MessageBox.Show("Nombre de contacts dans la collection : " + oContacts.Count.ToString());

Capacity

MessageBox.Show(oContacts.Capacity.ToString());

Références

Library (System.Collections.Generic.List): http://msdn.microsoft.com/fr-fr/library/d9hw1as6(VS.80).aspx

Le centre de development C#: http://msdn.microsoft.com/en-us/vstudio/hh341490.aspx

Un coach C# (comme il existe pour VB.NET,ASP.ET et VSTS) a vu le jour : http://msdn.microsoft.com/fr-fr/vstudio/bb409645(fr-fr)

Ce document intitulé « [.Net 2.0] - Tour d'horizon des membres des générics - System.Collections.Generic.List » issu de CodeS SourceS (codes-sources.commentcamarche.net) est mis à disposition sous les termes de la licence Creative Commons. Vous pouvez copier, modifier des copies de cette page, dans les conditions fixées par la licence, tant que cette note apparaît clairement.
Rejoignez-nous