0

I'm trying to sort a ListCollectionView but I can't get it to work. I have my own CustomSort which throws the following error:

Cannot implicitly convert type 'SceneComparer' to 'IComparer'. An explicit conversion exists. (Are you missing a cast?)

This is what my comparer looks like:

public class SceneComparer : IComparer<Scene>
{
    // Assumes that a scene is either numeric, or numeric + alpha.
    private readonly Regex sceneRegEx = new Regex(@"(\d*)(\w*)", RegexOptions.Compiled);

    public int Compare(Scene x, Scene y)
    {
        var firstSceneMatch = this.sceneRegEx.Match(x.SceneNumber);

        var firstSceneNumeric = Convert.ToInt32(firstSceneMatch.Groups[1].Value);
        var firstSceneAlpha = firstSceneMatch.Groups[2].Value;

        var secondSceneMatch = this.sceneRegEx.Match(y.SceneNumber);

        var secondSceneNumeric = Convert.ToInt32(secondSceneMatch.Groups[1].Value);
        var secondSceneAlpha = secondSceneMatch.Groups[2].Value;

        if (firstSceneNumeric < secondSceneNumeric)
        {
            return -1;
        }

        if (firstSceneNumeric > secondSceneNumeric)
        {
            return 1;
        }

        return string.CompareOrdinal(firstSceneAlpha, secondSceneAlpha);
    }
}

And here is the sorting in the ViewModel

private ListCollectionView _scenesNavigator;
public ListCollectionView ScenesNavigator
{
    get
    {
        _scenesNavigator = SceneCollectionView;
        _scenesNavigator.CustomSort = new SceneComparer(); ----> ERROR
        _scenesNavigator.IsLiveSorting = true;

        return _scenesNavigator;
    }
    set
    {
        _scenesNavigator = value; RaisePropertyChanged();
    }
}

public SourceViewModel()
{
        SceneCollectionView = Application.Current.Resources["SceneCollectionView"] as ListCollectionView;
}

How can I solve this issue?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Phil
  • 561
  • 2
  • 16
  • 29

1 Answers1

3

CustomSort is type of IComparer (msdn).

Here is example:

http://weblogs.asp.net/monikadyrda/wpf-listcollectionview-for-sorting-filtering-and-grouping

public class SortCreaturesByAge : IComparer
{
    public int Compare( object x, object y )
    {
        if( x as CreatureModel == null && y as CreatureModel == null )
        {
            throw new ArgumentException( "SortCreatures can 
                                    only sort CreatureModel objects." );
        }
        if( ((CreatureModel) x).Age > ((CreatureModel) y).Age )
        {
            return 1;
        }
        return -1;
    }
}
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
  • 1
    Shouldn't your check be an '||' (or) not an '&&' (and)? As it stands now, if one side is a CreatureModel but the other is not, or is null, you'll get an exception. – Mark A. Donohoe Jan 14 '17 at 07:53