Problem

Weird behavior with DataModelSortComparer

Posted 25 days ago by Avatar Antoine Picard

Hi,

I wanted to do something similar to the Sorting example in your sample so I created a class inheriting from DataModelSortComparer. Then I overriden the Compare function like this :

public override int Compare(IDataModel x, IDataModel y)
{
 // Sort the "Basic" category before anything else and "To Test" after anything else
 if (x is ICategoryModel xCategoryModel && y is ICategoryModel yCategoryModel)
 {
  switch (xCategoryModel.Name)
  {
   case "Basic":
    return 1;
   case "To Test":
    return -1;
   default:
    return 0;
  }
 }
}

 As I indicated in the comment, I want to have this kind of order for my 3 categories:
- Basic
- MyCat
- To Test

But what I have is :
- MyCat
- To Test
- Basic

Do you know why ? I can't find any logic about it.

AP

Edit : I tried with four categories and it's even weirder
- To Test
- Basic
- MyCat
- FourthOne

[Modified 25 days ago]


Comments (3)

Posted 25 days ago by Antoine Picard

Ok, found the problem myself, I also hae to return values depending of yCategoryModel.
So here's my final code :

public override int Compare(IDataModel x, IDataModel y)
{
 // Sort the "Basic" category before anything else and "To Test" after anything else
 if (x is ICategoryModel xCategoryModel && y is ICategoryModel yCategoryModel)
 {
  switch (xCategoryModel.Name)
  {
   case "Basic":
    return -1;
   case "To Test":
    return 1;
   default:
    switch (yCategoryModel.Name)
    {
     case "Basic":
      return 1;
     case "To Test":
      return -1;
     default:
      return 0;
    }
  }
 }
}

[Modified 25 days ago]

Posted 21 days ago by Actipro Software Support - Cleveland, OH, USA

Hi Antoine,

When you make a sort comparer, you need to have it handle each item.  You are returning 0 (meaning equal) for a number of things so that will sort them in random orders.  Instead of returning zero for things you don't care about, return base.Compare(x, y).  That will keep order properlly and will prevent the randomness you see.

Also note that WPF sort comparers will sometimes pass things in x or y.  You can't really predict, so you need to handle both x and y scenarios.  Your code was originally only handling x but as you saw later you need to do both.  And also I think you originally had it backwards in that -1 should be for first, and 1 is for last and corrected that in the latter code.


Actipro Software Support
Posted 21 days ago by Antoine Picard

Hi !

thanks for your feedback and your explanations ! I'll change this 0 stuff :)

And yes it was more intuitive for me to have the 1 at highest place and -1 lowest :) but still ok !

Information The latest build of this product (2018.1 build 0674) was released 4 days ago, which was after the last post in this thread.

Add a Comment

Please log in to a validated account to post comments.