Calendrier

Novembre 2009
L M M J V S D
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            
<< < > >>

Présentation

Recherche

W3C

  • Flux RSS des articles

C# 2.0

Au coeur des dictionnaires - Article Developpez.com

http://mehdi-fekih.developpez.com/articles/dotnet/dictionnaires/
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
BindingList et IEditableObject
pour l’edition facile dans les DataGridView
System.ComponentModel
 
-          BindingList 
-          IEditableObject : dispose des méthodes BeginEdit,EndEdit,CancelEdit automatiquement appelées lors de l’édition dans le datagridview
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
 
namespace IEditableDataGridView
{
    public class ContactCollection : BindingList<Contact>
    {
 
        public ContactCollection()
        {
            // AJOUT > autorise ou non l'ajout de nouveaux eleemnts
            this.AllowNew = true;
 
            // MODIFICATION > à false empeche l'edition des elements de la liste
            this.AllowEdit = true;
 
            // SUPPRESSION > autorise ou non la suppression d'element de la list
            this.AllowRemove = true;
        }
 
 
        protected override object AddNewCore()
        {
            Contact c = new Contact();
            this.Add(c);
            return c;
        }
    }
    public class Contact : IEditableObject
    {
        private int _contactID;
 
        public int ContactID
        {
            get { return _contactID; }
            set { _contactID = value; }
        }
        private string _contactName;
 
        public string ContactName
        {
            get { return _contactName; }
            set { _contactName = value; }
        }
        private string _contactFirstName;
 
        public string ContactFirstName
        {
            get { return _contactFirstName; }
            set { _contactFirstName = value; }
        }
        private Nullable<int> _contactAge;
 
        public Nullable<int> ContactAge
        {
            get { return _contactAge; }
            set { _contactAge = value; }
        }
 
        public Contact()
        { }
        public Contact(int contactID,string contactName,string contactFirstName,Nullable<int> contactAge)
        {
            this.ContactID = contactID;
            this.ContactName = contactName;
            this.ContactFirstName = contactFirstName;
            this.ContactAge = contactAge;
        }
 
        #region IEditableObject Membres
 
        public void BeginEdit()
        {
          
        }
 
        public void CancelEdit()
        {
        }
 
        public void EndEdit()
        {
        }
 
        #endregion
 
    }
}
 
Exemples (code Form1)
       ContactCollection Contacts = new ContactCollection();
 
        private void button1_Click(object sender, EventArgs e)
        {
 
            Contacts.Add(new Contact(1, "Romagny", "jerome", 31));
            Contacts.Add(new Contact(2, "Bellin", "marie", 25));
            Contacts.Add(new Contact(1, "Durand", "paul", 40));
 
            dataGridView1.DataSource = Contacts;         
        }
 
        private void button2_Click(object sender, EventArgs e)
        {           
            Contacts.AddNew();
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            Contacts.CancelNew(Contacts.Count -1);
        }
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Classe de management Undo Redo pour les listes generics et plus si affinité :p
Je viens de développer ma propre classe de management des actions undo redo, celle-ci est particulièrement appropriée aux listes génériques
En fait ce n’est qu’un échauffement vu que mon but sera d’implémenter ce style de classe mais pour gérer la treeview Xml des éditeurs que j’ai développé
Donc cette classe prend en charge les actions undo/redo autrement dit (annuler/rétablir) pour
-          Add
-          Insert
-          InsertRange
-          Update
-          Remove
-          RemoveRange
En fait j’ai fais un test avec mon éternelle classe contact, ainsi on peut ajouter 1 ou plusieurs contacts,en modifier un,etc. et annuler ou retablir les actions qui viennent d’etre effectuée sur la liste generique principale
Tout n’est pas parfait encore et il y a des améliorations à faire .. 
UndoRedaManager.JPG
using System;
using System.Collections.Generic;
using System.Text;
 
namespace UndoRedo.test
{
    public class UndoRedoManager<T>
    {
        public static Stack<Action<T>> undoStack = new Stack<Action<T>>();
        public static Stack<Action<T>> redoStack = new Stack<Action<T>>();
 
        public static void Undo(List<T> t, T NewValue)
        {
            if (undoStack.Count > 0)
            {
                Action<T> oAction = undoStack.Pop();
 
                if (oAction.ActionType == ActionType.InsertRange)
                {
                    while (oAction.ActionType == ActionType.InsertRange)
                    {
                        Action<T> InsertAction = new Action<T>(oAction.Index, oAction.Value, ActionType.RemoveRange);
                        redoStack.Push(InsertAction);
                        t.RemoveAt(oAction.Index);
 
                        if (CanUndo())
                        {
                            oAction = undoStack.Peek();
                            if (oAction.ActionType == ActionType.InsertRange)
                                oAction = undoStack.Pop();
                            else
                                return;
                        }
                        else
                            return;
                    }
                }
                else if (oAction.ActionType == ActionType.RemoveRange)
                {
                    while (oAction.ActionType == ActionType.RemoveRange)
                    {
                        Action<T> InsertAction = new Action<T>(oAction.Index, oAction.Value, ActionType.InsertRange);
                        redoStack.Push(InsertAction);
                        t.Insert(oAction.Index, oAction.Value);
 
                        if (CanUndo())
                        {
                            oAction = undoStack.Peek();
                            if (oAction.ActionType == ActionType.RemoveRange)
                                oAction = undoStack.Pop();
                            else
                                return;
                        }
                        else
                            return;
                    }
                }
                else
                {
                    switch (oAction.ActionType)
                    {
                        case ActionType.Add:
                            Action<T> AddAction = new Action<T>(oAction.Index, oAction.Value, ActionType.Remove);
                            redoStack.Push(AddAction);
                            t.RemoveAt(oAction.Index);
                            break;
                        case ActionType.Update:
                            T OldValue = (T)oAction.Value;
                            Action<T> UpdateAction = new Action<T>(oAction.Index, NewValue, ActionType.Update);
                            redoStack.Push(UpdateAction);
                            t[oAction.Index] = OldValue;
                            break;
                        case ActionType.Remove:
                            Action<T> RemoveAction = new Action<T>(oAction.Index, oAction.Value, ActionType.Add);
                            redoStack.Push(RemoveAction);
                            t.Insert(oAction.Index, oAction.Value);
                            break;
                    }
                }
            }
        }
 
        public static void Redo(List<T> t,T NewValue)
        {
            if (redoStack.Count > 0)
            {
                Action<T> oAction = redoStack.Pop();
                if (oAction.ActionType == ActionType.InsertRange)
                {
                    while (oAction.ActionType == ActionType.InsertRange)
                    {
                        Action<T> InsertAction = new Action<T>(oAction.Index, oAction.Value, ActionType.RemoveRange);
                        undoStack.Push(InsertAction);
                        t.RemoveAt(oAction.Index);
 
                        if (CanRedo())
                        {
                            oAction = redoStack.Peek();
                            if (oAction.ActionType == ActionType.InsertRange)
                                oAction = redoStack.Pop();
                            else
                                return;
                        }
                        else
                            return;
                    }
                }
                else if (oAction.ActionType == ActionType.RemoveRange)
                {
                    while (oAction.ActionType == ActionType.RemoveRange)
                    {
                        Action<T> InsertAction = new Action<T>(oAction.Index, oAction.Value, ActionType.InsertRange);
                        undoStack.Push(InsertAction);
                        t.Insert(oAction.Index, oAction.Value);
 
                        if (CanRedo())
                        {
                            oAction = redoStack.Peek();
                            if (oAction.ActionType == ActionType.RemoveRange)
                                oAction = redoStack.Pop();
                            else
                                return;
                        }
                        else
                            return;
                    }
                }
                else
                {
                    switch (oAction.ActionType)
                    {
                        case ActionType.Add:
                            Action<T> AddAction = new Action<T>(oAction.Index, oAction.Value, ActionType.Remove);
                            undoStack.Push(AddAction);
                            t.RemoveAt(oAction.Index);
                            break;
                        case ActionType.Update:
                            T OldValue = (T)oAction.Value;
                            Action<T> UpdateAction = new Action<T>(oAction.Index, NewValue, ActionType.Update);
                            undoStack.Push(UpdateAction);
                            t[oAction.Index] = OldValue;
                            break;
                        case ActionType.Remove:
                            Action<T> RemoveAction = new Action<T>(oAction.Index, oAction.Value, ActionType.Add);
                            undoStack.Push(RemoveAction);
                            t.Insert(oAction.Index, oAction.Value);
                            break;
                    }
                }
            }
        }
 
        public static void pushAction(Action<T> t)
        {
            undoStack.Push(t);
        }
        public static void pushAction(List<Action<T>> t)
        {
            foreach(Action<T> a in t)
            undoStack.Push(a);
        }
 
        public static bool CanUndo()
        {
            bool result=false;
            if (undoStack.Count > 0)
                result = true;
            return result;
        }
        public static bool CanRedo()
        {
            bool result = false;
            if (redoStack.Count > 0)
                result = true;
            return result;
        }
 
    }
 
    public class Action<T>
    {
     private int _index;
 
        public int Index
        {
            get { return _index; }
            set { _index = value; }
        }
 
        private T _value;
 
        public T Value
        {
            get { return _value; }
            set { _value = value; }
        }
 
        private ActionType _actionType;
 
        public ActionType ActionType
        {
            get { return _actionType; }
            set { _actionType = value; }
        }
 
        public override string ToString()
        {
            return Index.ToString() + "    " + Value.ToString() + "    " + ActionType.ToString();
        }
 
        public Action()
        { }
        public Action(int index, T value, ActionType actionType)
        {
            this.Index = index;
            this.Value = value;
            this.ActionType = actionType;
        }
    }
 
    public enum ActionType
    {
        Add,
        Update,
        Remove,
        InsertRange,
        RemoveRange
    }
}
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Code de la form
Je trouve qu’il y a encore beaucoup trop de code à saisir et dans la form
 List<Contact> Contacts = new List<Contact>();
 
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // ACTIONS UTILISATEURS ------------------------------------->
        private void btnAddContact_Click(object sender, EventArgs e)
        {
            Contact oContact = new Contact(Convert.ToInt32(txtContactID.Text), txtContactName.Text);
            Contacts.Add(oContact);
            Contact c = new Contact(Convert.ToInt32(txtContactID.Text), txtContactName.Text);
 
            Action<Contact> oAction = new Action<Contact>(Contacts.Count - 1, c, ActionType.Add);
            UndoRedoManager<Contact>.pushAction(oAction);
 
            if (UndoRedoManager<Action<Contact>>.redoStack.Count > 0)
                UndoRedoManager<Action<Contact>>.redoStack.Clear();
            PostAll();
        }
 
        private void btnInsert_Click(object sender, EventArgs e)
        {
            Contact oContact = new Contact(Convert.ToInt32(txtContactID.Text), txtContactName.Text);
            Contacts.Insert(dataGridView1.CurrentRow.Index, oContact);
            Action<Contact> oAction = new Action<Contact>(dataGridView1.CurrentRow.Index, oContact, ActionType.Add);
            UndoRedoManager<Contact>.pushAction(oAction);
            if (UndoRedoManager<Action<Contact>>.redoStack.Count > 0)
                UndoRedoManager<Action<Contact>>.redoStack.Clear();
            PostAll();
        }
        private void btnInsertRange_Click(object sender, EventArgs e)
        {
            List<Contact> cs = new List<Contact>();
            cs.Add(new Contact(10, "Bill"));
            cs.Add(new Contact(11, "Boule"));
 
            List<Action<Contact>> oActions = new List<Action<Contact>>();
            foreach (Contact c in cs)
            {
                Contacts.Add(c);
                oActions.Add(new Action<Contact>(Contacts.Count - 1, c, ActionType.InsertRange));
            }
            UndoRedoManager<Contact>.pushAction(oActions);
 
            PostAll();
        }
        private void btnUpdateContact_Click(object sender, EventArgs e)
        {
            int indexContact = FindContact(Convert.ToInt32(txtContactID.Text));
            Contact c = new Contact(Contacts[indexContact].ContactID, Contacts[indexContact].ContactName);
            Action<Contact> oAction = new Action<Contact>(indexContact, c, ActionType.Update);
            UndoRedoManager<Contact>.pushAction(oAction);
 
            Contacts[indexContact].ContactID = Convert.ToInt32(txtContactID.Text);
            Contacts[indexContact].ContactName = txtContactName.Text;
            if (UndoRedoManager<Action<Contact>>.redoStack.Count > 0)
                UndoRedoManager<Action<Contact>>.redoStack.Clear();
            PostAll();
        }
 
        private void btnRemoveContact_Click(object sender, EventArgs e)
        {
            int indexContact = FindContact(Convert.ToInt32(txtContactID.Text));
            Action<Contact> oAction = new Action<Contact>(indexContact, Contacts[indexContact], ActionType.Remove);
            UndoRedoManager<Contact>.pushAction(oAction);
            Contacts.RemoveAt(indexContact);
            if (UndoRedoManager<Action<Contact>>.redoStack.Count > 0)
                UndoRedoManager<Action<Contact>>.redoStack.Clear();
            PostAll();
        }
        public int FindContact(int contactID)
        {
            int result = -1;
            int index = 0;
            foreach (Contact c in Contacts)
            {
                if (c.ContactID == contactID)
                    result = index;
 
                index += 1;
            }
            return result;
        }
        public void PostAll()
        {
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = Contacts;
 
            try
            {
                listBox1.Items.Clear();
                System.Collections.IEnumerator oEnum = UndoRedoManager<Action<Contact>>.undoStack.GetEnumerator();
                while (oEnum.MoveNext())
                {
                    Action<Contact> a = (Action<Contact>)oEnum.Current;
                    Contact c = (Contact)a.Value;
                    listBox1.Items.Add(a.Index.ToString() + "    " + c.ContactID.ToString() + " " + c.ContactName + "     " + a.ActionType.ToString());
                }
                listBox2.Items.Clear();
                System.Collections.IEnumerator oEnum2 = UndoRedoManager<Action<Contact>>.redoStack.GetEnumerator();
                while (oEnum2.MoveNext())
                {
                    Action<Contact> a = (Action<Contact>)oEnum2.Current;
                    Contact c = (Contact)a.Value;
                    listBox2.Items.Add(a.Index.ToString() + "    " + c.ContactID.ToString() + " " + c.ContactName + "     " + a.ActionType.ToString());
                }
            }
            catch
            { }
 
        }
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                Contact c = Contacts[FindContact(Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value))];
                if (c != null)
                {
                    txtContactID.Text = c.ContactID.ToString();
                    txtContactName.Text = c.ContactName;
                }
            }
            catch
            { }
        }
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // UNDO <---------------------------------
        private void btnUndo_Click(object sender, EventArgs e)
        {
            if (UndoRedoManager<Contact>.CanUndo())
            {
                Action<Contact> oAction = UndoRedoManager<Contact>.undoStack.Peek();
                Contact NewContact = new Contact(Contacts[oAction.Index].ContactID, Contacts[oAction.Index].ContactName);
                UndoRedoManager<Contact>.Undo(Contacts, NewContact);
                PostAll();
            }
        }
        // REDO ------------------------------------->
        private void btnRedo_Click(object sender, EventArgs e)
        {
            if (UndoRedoManager<Contact>.CanRedo())
            {
                Action<Contact> oAction = UndoRedoManager<Contact>.redoStack.Peek();
                Contact c = (Contact)oAction.Value;
                Contact NewContact = new Contact(c.ContactID, c.ContactName);
                UndoRedoManager<Contact>.Redo(Contacts, NewContact);
               PostAll();
            }
        }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
[.NET 2.0] trier et filtrer avec les generics
I – Filtrer
Le filtre consiste à comparer chacun des elements de la liste par rapport à une condition (exemple StarstWith(« A »)),selon que cette condition est est remplie ou non ,true ou false indique en retour si l’objet en cours doit etre ajouté à la liste résultat
1 – avec les méthodes anonymes
 
private void button1_Click(object sender, EventArgs e)
        {
            // 1 avec méthode anonyme
            List<Contact> result = Contacts.FindAll(delegate(Contact oContact)
            {
                return oContact.ContactAge > 20;
            });
            dataGridView1.DataSource = result;
        }
 
2 – avec les Predicates (System.Predicate<T>)
Les Predicate ne sont en fait rien d’autre que des delegues generics, qui attendent une méthode devant respectant la signature attendue , c'est-à-dire retournant un bool et recevant en paramètre un objet du typeT defini explicitement
private void button1_Click(object sender, EventArgs e)
        {
            // 2 avec un Predicate (qui est un delegue)
            // Predicate<T> predicate = new Predicate<T>(bool(T) target)
            Predicate<Contact> predicate = new Predicate<Contact>(FindContacts);
            List<Contact> result = Contacts.FindAll(predicate);
            dataGridView1.DataSource = result;
        }
        public bool FindContacts(Contact oContact)
        {
         return oContact.ContactAge > 20;
        }
 
3 – en passant tout simplement une méthode respectant la signature des predicates
private void button1_Click(object sender, EventArgs e)
        {           
            List<Contact> result = Contacts.FindAll(FindContacts);
            dataGridView1.DataSource = result;
        }
        public bool FindContacts(Contact oContact)
        {
         return oContact.ContactAge > 20;
        }
 
Format de la méthode :
        public bool nommethod(T obj)
        {
         // test
         Return booleen;
        }
 
II Trier
1 – avec les méthodes anonymes
private void button2_Click(object sender, EventArgs e)
        {          
            Contacts.Sort(delegate(Contact x, Contact y)
            {
                return Comparer<string>.Default.Compare(x.ContactName, y.ContactName);
            });
        }
 
2 – avec Comparison<T>
Ici la méthode va servir à comparer deux instances de la liste generic par rapport à un property, le résultat de la comparaison sera soit
0 (equivalents)          -1          1
private void button2_Click(object sender, EventArgs e)
        {
            // Comparison<T> comparison =new Comparison<T>(int (T,T)target);
            Comparison<Contact> comparison = new Comparison<Contact>(SortContacts);
            Contacts.Sort(comparison);
            dataGridView1.DataSource = Contacts;
        }
        public int SortContacts(Contact x, Contact y)
        {
            return Comparer<string>.Default.Compare(x.ContactName, y.ContactName);
        }
 
3 – en passant tout simplement une méthode respectant la signature de comparison<T>
private void button2_Click(object sender, EventArgs e)
        {         
            Contacts.Sort(SortContacts);
            dataGridView1.DataSource = Contacts;
        }
        public int SortContacts(Contact x, Contact y)
        {
            return Comparer<string>.Default.Compare(x.ContactName, y.ContactName);
        }
 
Format de la méthode de tri
La méthode doit retourner un int
Le type K est le type des properties comparés(c’est un type value :int,string,etc.)
        public int nommethod(T x, T y)
        {
            return Comparer<K>.Default.Compare(x.property, y.property);
        }
 
Bien sur finalement et c’est l’objectif on peut combiner le tri et le filtre de manière de plus en plus complexe
Note : Avec Linq To Objects  lorsqu’on effectue un tri (clause Where) le tri est effectué sur la liste retournée en resultat et non sur la liste d’origine
En utilisant les méthodes décrites ici on peut trier aussi une liste autre que la liste d’origine par exemple la liste obtenue après un filtre mais si on utilise un IComparer ou IComparable défni directement dans la classe (ex : dans la classe contact) alors ce sera la liste d’origine qui sera trié, c’est à savoir quand même
Par Romagny13
Ecrire un commentaire - Voir les 1 commentaires - Recommander
Une classe de tri generic
 
public class GenericComparer<T> : IComparer<T>
    {
        private string propertyName;
        private SorterMode sorterMode;
 
        public GenericComparer(string propertyName, SorterMode direction)
            : base()
        {
            this.propertyName = propertyName;
            sorterMode = direction;
        }
 
        #region IComparer<T> Members
 
        public int Compare(T x, T y)
        {
            if (x == null)
            {
                if (y != null)
                    return -1;
                return 0;
            }
            if (y == null)
                return 1;
            if ((x is T) && (y is T))
            {
                IComparable value1 = x.GetType().GetProperty(propertyName).GetValue(x, null) as IComparable;
                IComparable value2 = y.GetType().GetProperty(propertyName).GetValue(y, null) as IComparable;
 
                if (sorterMode == SorterMode.Ascending)
                    return value1.CompareTo(value2);
                else
                    return value2.CompareTo(value1);
 
            }
            return 0;
        }
 
        #endregion
    }
 
    public enum SorterMode
    {
        Ascending,
        Descending
    }
 
Utilisation
           List<Contact> Contacts = new List<Contact>();
            Contacts.Add(new Contact(1, "Romagny"));
            Contacts.Add(new Contact(2, "Bellin"));
            Contacts.Add(new Contact(3, "Mariz"));
            Contacts.Add(new Contact(4, "Benon"));
            Contacts.Add(new Contact(5, "Felin"));
 
           GenericComparer<Contact> GenericComparer = new GenericComparer<Contact>("ContactName", SorterMode.Ascending);
            Contacts.Sort(GenericComparer);
 
            dataGridView1.DataSource = Contacts;
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Classe de sérialization générique
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Cs2PredicateHelper
{
    ///<summary>
    /// Classe de sérialization générique
    ///</summary>
    ///<typeparam name="T">Type générique</typeparam>
    public class SerializeManager<T>
    {
        public static void Serialize(T obj,string Path)
        {
            System.Xml.Serialization.XmlSerializer oXmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            System.IO.StreamWriter oStreamWriter = new System.IO.StreamWriter(Path);
            oXmlSerializer.Serialize(oStreamWriter, obj);
            oStreamWriter.Close();
        }
        public static T Deserialize(string Path)
        {
            System.Xml.Serialization.XmlSerializer oXmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            System.IO.StreamReader oStreamReader = new System.IO.StreamReader(Path);
            T obj = (T)oXmlSerializer.Deserialize(oStreamReader);
            oStreamReader.Close();
            return obj;
        }
    }
}
 
Utilisation
           // Serialization
            SerializeManager<List<Contact>>.Serialize(oContacts, "c:/test.xml");
 
            // Deserialization
           List<Contact> c= SerializeManager<List<Contact>>.Deserialize("c:/test.xml");
           dataGridView1.DataSource = c;
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Créer une fonction predicate pouvant recevoir des arguments
 
Grace aux méthodes anonymes
        List<Contact> SelectContact = oContacts.FindAll(delegate(Contact oContact)
    {
        return WhereContactNameStartWith(oContact, "R");
    }
    );
 
private bool WhereContactNameStartWith(Contact oContact, string Value)
        {
            bool bResult = false;
            if (oContact.ContactName.StartsWith(Value))
                bResult = true;
            else
                bResult = false;
            return bResult;
        }
 
Autrement on a la classique classe Contact + une liste générique de contact oContacts
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Cs2Objects
{
    public class Contact
    {
        private int _ContactID;
 
        public int ContactID
        {
            get { return _ContactID; }
            set { _ContactID = value; }
        }
 
        private string _ContactName;
 
        public string ContactName
        {
            get { return _ContactName; }
            set { _ContactName = value; }
        }
 
        private string _ContactFirstName;
 
        public string ContactFirstName
        {
            get { return _ContactFirstName; }
            set { _ContactFirstName = value; }
        }
 
        private Nullable<int> _ContactAge;
 
        public Nullable<int> ContactAge
        {
            get { return _ContactAge; }
            set { _ContactAge = value; }
        }
 
        public Contact()
        { }
        public Contact(int ContactID, string ContactName, string ContactFirstName, Nullable<int> ContactAge)
        {
            _ContactID = ContactID;
            _ContactName = ContactName;
            _ContactFirstName = ContactFirstName;
            _ContactAge = ContactAge;
        }
 
    }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
[.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
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é
            oContacts.RemoveAt(1);
 
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;
 
            }
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
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
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
Ou encore regarder cette source ;)
 
 
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
            oContacts.Reverse();
 
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)
Le centre de development C#
un coach C# (comme il existe pour VB.NET,ASP.ET et VSTS) a vu le jour :
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander

Webcast - C# 2.0 un an aprés (Mitzu Furuta, mercredi du développement)

je mets le lien ici pour permettre un accés direct au webcast (bien que je pense que pas mal de monde a du déja le suivre)

http://www.microsoft.com/france/msdn/vcsharp/mercredis_developpement-csharp2.mspx

Par Romagny13
- Voir les 0 commentaires - Recommander
Créer un blog sur over-blog.com - Contact - C.G.U. - Rémunération en droits d'auteur - Signaler un abus