0

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..

Mark D
  • 279
  • 1
  • 7
  • 17

1 Answers1

1

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;
   }
}
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • Dead link to Bea Stollnitz (what a loss!!!), can you please post an example or working link? – Hannish Jun 24 '16 at 09:44
  • @Hannish - Thanks. I have updated the link. Also post an example to avoid stale link issue in future. Hope that helps.!! – Rohit Vats Jun 24 '16 at 16:57
  • Thank you, you're most kind. By the way, do you know what happened to Bea's blog? It's huge that it disappeared... – Hannish Jun 24 '16 at 21:42