Mark D
Mark D

Reputation: 289

WPF CollectionViewSource sorting issues with null values

I've got a collectionviewsource whose source is an observable collection and i'm sorting like so ;

_viewSource.SortDescriptions.Add(new SortDescription() { PropertyName ="PropertyName", Direction = ListSortDirection.Ascending });

this all works great until I attempt to sort by a property in the list that has a null value. I then get a InvalidOperationException, "Failed to compare two elements in the array"

Do I have to implement my own IComparer class in order to work around the null issue or am I missing a trick?

Thanks in advance..

Upvotes: 0

Views: 1654

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81243

Yeah to handle null values you have to write down your own custom sorter implementing IComparer. Can refer to this one just in case - IComparer sample.


private class sortYearAscendingHelper : IComparer
{
   int IComparer.Compare(object a, object b)
   {
      car c1=(car)a;
      car c2=(car)b;
      if(c1.year == null && c2.year == null)
         return 0;
      if(c1.year == null && c2.year != null)
         return -1;
      if(c1.year != null && c2.year == null)
         return 1;
      if (c1.year > c2.year)
         return 1;
      if (c1.year < c2.year)
         return -1;
      else
         return 0;
   }
}

Upvotes: 1

Related Questions