[.NET 2.0] - Tour d horizon des membres des générics
System.Collections.Generic.List
Sommaire :
Ce que j utilise pour les exemples
I - Ajout
II - Modification
III - Suppression
IV - Consultation
V – Chercher/Trouver
VI – trier
VII – Conversions
VIII – autres
Ce que j utilise pour les exemples
Code de la form principal
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 emploie 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
}}
|
I - Ajout
A – Ajouter un élément à la collection
1 – 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"));
|
2 – Insert()
// insérer un element à l index spécifié
oContacts.Insert(2, new Contact(8, "Perrot", "Alphonse", "aperrot@hotmail.fr"));
|
B – Ajout de collection à la collection
1 – 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);
|
2– 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);
|
II - 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";
|
III - Suppression
1 – 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));
|
2 – RemoveAt() – pour supprimer l élément à l index de la collection spécifié
3 – RemoveAll() – supprimer tous les éléments de la collection respectant un prédicat
oContacts.RemoveAll(StartWith);
|
4 – 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);
|
5 – Clear() – supprimer tous les éléments de la collection
// 6 Clear() : supprime tous les éléments de la collection
oContacts.Clear();
|
IV - Consultation
1 – Boucles for et foreach
foreach (Contact oContact in oContacts)
{
}
|
for (int nCount = 0; nCount <= oContacts.Count - 1; nCount++)
{
}
|
2 – GetEnumerator()
string smessage = string.Empty;
IEnumerator<Contact> oContactsEnumerator = oContacts.GetEnumerator();
while (oContactsEnumerator.MoveNext())
{
smessage += oContactsEnumerator.Current.ToString() + Environment.NewLine;
}
|
3 – ForEach()
string smessage=string.Empty;
oContacts.ForEach(delegate(Contact oContact)
{
smessage += oContact.ToString() + Environment.NewLine;
}
);
MessageBox.Show(smessage);
|
4 – AsReadOnly() – pour obtenir la collection mais ne pouvant être que consultée
//AsReadOnly() retourne la collection mais en lecture seule (ici l edition dans le datagridview sera impossible)
dataGridView1.DataSource = oContacts.AsReadOnly();
|
5 – 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);
|
V – Chercher/Trouver
1 – 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 est renvoyé)
Contact oContact = oContacts.Find(StartWith);
MessageBox.Show(oContact.ToString());
|
2 – IndexOf () – trouver l index d un élément
Contact oContact = oContacts.FindLast(StartWith);
int nIndex =oContacts.IndexOf(oContact);
|
3 – FindIndex() – renvoie l index (int) de la position du premier élément respectant un prédicat
MessageBox.Show(oContacts.FindIndex(StartWith).ToString());
|
4 – FindLast() – trouver le dernier élément respectant un prédicat
MessageBox.Show(oContacts.FindLast(StartWith).ToString());
|
5 – LastIndexOf() – trouver l index du dernier element de la collection respectant un prédicat
Contact oContact = oContacts.FindLast(StartWith);
int nIndex =oContacts.LastIndexOf(oContact);
|
6 – FindLastIndex() – renvoie l index (int) du dernier élément de la collection respectant un prédicat
MessageBox.Show(oContacts.FindLastIndex(StartWith).ToString());
|
7 – FindAll() – Trouver tous les elements (FindAll() retourne une liste générique) respectant un prédicat
dataGridView1.DataSource = oContacts.FindAll(StartWith);
|
VI – trier
1 - Avec l interface IComparable implémentée par la classe Contact
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));
|
VII – Conversions
1 – CopyTo() – copier vers un tableau la collection
Contact[] ContactArrray;
ContactArrray = new Contact[5];
oContacts.CopyTo(ContactArrray);
dataGridView1.DataSource = ContactArrray;
|
2 – ToArray() – convertir en tableau la collection
Contact[] ContactArrray = oContacts.ToArray();
|
3 –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; }
}
}
|
VIII – autres
1 – Contains() – Savoir si la collection contient un element
Contact oContact = oContacts.Find(StartWith);
MessageBox.Show(oContacts.Contains(oContact).ToString());
|
2 – Exists() – renvoie un Bool indiquant si au moins un element de la collection respecte le prédicat
MessageBox.Show(oContacts.Exists(StartWith).ToString());
|
3 –TrueForAll() – renvoie un bool indiquant si tous les éléments de la collection respecte un prédicat
MessageBox.Show(oContacts.TrueForAll(StartWith).ToString());
|
4 – Equals() – compare 2 éléments et renvoie un bool
MessageBox.Show(oContacts[1].Equals(oContact).ToString());
|
5 – GetType() – renvoie le type de la collection
MessageBox.Show(oContacts.GetType().ToString());
|
6 Reverse () – méthode permettant inverser les éléments de la collection
7– Count
MessageBox.Show("Nombre de contacts dans la collection : " + oContacts.Count.ToString());
|
8– Capacity
MessageBox.Show(oContacts.Capacity.ToString());
|
Liens
Library (System.Collections.Generic.List)
http://msdn2.microsoft.com/fr-fr/library/d9hw1as6(VS.80).aspx
Le centre de development C#
http://msdn2.microsoft.com/fr-fr/vcsharp/default.aspx
un coach C# (comme il existe pour VB.NET,ASP.ET et VSTS) a vu le jour :
http://msdn2.microsoft.com/fr-fr/vcsharp/bb409645.aspx