WPF custom sort

Using IComparer for fast sorting on listbox

ListCollectionView allows to sort listbox in wpf to sort. You bind the listbox to the instance of ListCollectionView.

View.SortDescriptions.Add(new SortDescription(){ PropertyName = columnName,ListSortDirection.Descending});

The above technique uses reflection to sort the ListCollectionView so if you have a large data collection , this can be very slow.

For faster sorting you can use CustomSort.

var sortComparer = new UserComparer ();
View.CustomSort = sortComparer;

Classes
————————————————–

public abstract class SortComparer : IComparer
{
public string SortColumn;

public ListSortDirection Direction;

public abstract int Compare(object x, object y);

}

public class UserComparer : SortComparer

{

public override int Compare(object x, object y)

{

var tx = (User)x;

var ty = (User)y;

int ret = 0;

switch (SortColumn)

{

case "UserName":

{

ret = Direction == ListSortDirection.Ascending ? tx.UserName.CompareTo(ty.UserName) : ty.UserName.CompareTo(tx.UserName);

break;

}

}

return ret;

}

}
, ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Share to Facebook Share to Twitter Stumble It Share on Tumblr Digg More...