Overblog Suivre ce blog
Editer l'article Administration Créer mon blog

Présentation

  • : Romagny13 - Du .NET,du pur .NET
  • Romagny13 - Du .NET,du pur .NET
  • : Cycle de progression Faire (quelque chose qui marche) -> comprendre ce que l’on fait/comment cela marche -> pousser plus loin les notions
  • Contact

Recherche

Articles Récents

7 juillet 2007 6 07 /07 /juillet /2007 20:09
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;
 

Partager cet article

Repost 0
Published by Romagny13 - dans C 1.0- 2.0- 3.0
commenter cet article

commentaires