Torna al Thread
public class SortableBindingList<T> : BindingList<T>
{
private ListSortDirection m_Direction = ListSortDirection.Ascending;
private PropertyDescriptor m_SortProperty;
#region costruttori
public SortableBindingList() { }
public SortableBindingList(IEnumerable<T> lista)
{
foreach (T obj in lista)
this.Add(obj);
}
#endregion
private int Confronto(T obj1, T obj2)
{
int ris = 0;
if ((m_SortProperty.GetValue(obj1) as IComparable) != null) //--- ordino solo se è ordinabile
ris = ((IComparable)m_SortProperty.GetValue(obj1)).CompareTo(m_SortProperty.GetValue(obj2));
if (m_Direction == ListSortDirection.Descending)
ris = -ris;
return ris;
}
protected override ListSortDirection SortDirectionCore
{ get { return m_Direction; } }
protected override PropertyDescriptor SortPropertyCore
{ get { return m_SortProperty; } }
protected override bool SupportsSortingCore
{ get { return true; } }
protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
{
List<T> items = this.Items as List<T>;
if (items != null)
{
m_Direction = direction;
m_SortProperty = property;
items.Sort(new Comparison<T>(Confronto));
}
}
public void Sort(string nomeProprieta)
{
Sort(nomeProprieta,false);
}
public void Sort(string nomeProprieta,bool descending)
{
List<T> items = this.Items as List<T>;
items.Sort(
delegate(T obj1, T obj2) {
IComparable val1 = null;
IComparable val2 = null;
if (nomeProprieta.Contains("."))
{
string[] proprieta = nomeProprieta.Split('.');
object oggettoInterno1 = obj1.GetType().GetProperty(proprieta[0]).GetValue(obj1, null);
if (oggettoInterno1 != null)
val1 = oggettoInterno1.GetType().GetProperty(proprieta[1]).GetValue(oggettoInterno1, null) as IComparable;
object oggettoInterno2 = obj2.GetType().GetProperty(proprieta[0]).GetValue(obj2, null);
if (oggettoInterno2 != null)
val2 = oggettoInterno2.GetType().GetProperty(proprieta[1]).GetValue(oggettoInterno2, null) as IComparable;
}
else
{
val1 = obj1.GetType().GetProperty(nomeProprieta).GetValue(obj1, null) as IComparable;
val2 = obj2.GetType().GetProperty(nomeProprieta).GetValue(obj2, null) as IComparable;
}
if (val1 == null)
return 0;
if (!descending)
return val1.CompareTo(val2);
else
return val2.CompareTo(val1);
}
);
}
public T Find(Predicate<T> predicato)
{
List<T> items = this.Items as List<T>;
T trovato = default(T);
if(items != null)
trovato = items.Find(predicato);
return trovato;
}
}