Comparer dynamique pour tri List
CodeKeep C# Feed Agosto 14th, 2008
Description: Comparer dynamique pour tri sur plusieurs attributs dans GridView avec listeLink: http://www.codekeep.net/snippets/b17d6804-6f6c-4474-926a-6abf3cf6dd62.aspx
/// <summary>
/// CplProduitComparer is used to sort the generic collection of the CplProduit class
/// </summary>
public class CplProduitComparer : IComparer<CplProduit>
{
#region Constructor
public CplProduitComparer(string p_propertyName)
{
//We must have a property name for this comparer to work
this.PropertyName = p_propertyName;
}
#endregion
#region Property
private string _propertyName;
public string PropertyName
{
get { return _propertyName; }
set { _propertyName = value; }
}
#endregion
#region IComparer<CplProduit> Members
/// <summary>
/// This comparer is used to sort the generic comparer
/// The constructor sets the PropertyName that is used
/// by reflection to access that property in the object to
/// object compare.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(CplProduit x, CplProduit y)
{
Type t = x.GetType();
PropertyInfo val = t.GetProperty(this.PropertyName);
if (val != null)
{
return Comparer.DefaultInvariant.Compare(val.GetValue(x, null), val.GetValue(y, null));
}
else
{
throw new Exception(this.PropertyName + " is not a valid property to sort on. It doesn't exist in the Class.");
}
}
#endregion
}