I have the following situation: I get a list of items which should be sorted by the SortId
property.
I have implemented the IComparable<T>
interface in my ItemViewModels, so that I can use Comparer.Default
in my ICollectionView.CustomSort
property to apply the sorting without using reflection (which PropertySortDescription
does).
Now, my problem is that the items sometimes do not have the SortId
property set because they should simply be sorted in the order they appear in the collection. However, instead of keeping the order, the items are displayed in reverse order or sometimes completely mixed - this seems to depend on the number of items.
Is there a way to avoid this behavior? If I do not apply any sorting, the items appear in the correct order. However, I would have to dynamically turn the sorting on or off, depending on the items' SortId
properties - which I do not like at all... Any other ideas?
By updating the implementation of CompareTo
method you can guarantee the sort order of those objects without SortId defined
eg
public class MyItem : IComparable
{
public int? SortId { get; set; }
public int CompareTo(object other)
{
if (SortId == null)
return -1;
MyItem otherItem = other as MyItem;
if (otherItem == null || otherItem.SortId == null)
return 1;
return SortId.Value.CompareTo(otherItem.SortId.Value);
}
}
above will guarantee that the objects without sort id will be smaller then other