Search code examples
c#wpfsortinglistcollectionview

ListCollectionView CustomSort 2 conditions


I have a ListCollectionView in my ViewModel which I bind it to a ListBox. Let's say I have a collection of strings, where I first want to sort them by string length, then by alphabetical order. How should I do it?

Currently I managde to sort it by length using CustomSort by implementing my own IComparer class, but how can I do it such that it is also in alphabetical order for the strings with the same length.


Solution

  • You can easily use LINQ to do that:

    List<string> list = GetTheStringsFromSomewhere();
    List<string> ordered = list.OrderBy(p => p.Length).ThenBy(p => p).ToList();
    

    EDIT:

    You mentioned CustomSort and SortDescription in your comment. I think (untested) you should be able to achieve the same result by rolling your own Comparer:

    public class ByLengthAndAlphabeticallyOrderComparer : IComparer
    {
        int IComparer.Compare(Object x, Object y)
        {
            var stringX = x as string;
            var stringY = y as string;
    
            int lengthDiff = stringX.Length - stringY.Length;           
            if (lengthDiff !=)
            {
                return lengthDiff < 0 ? -1 : 1; // maybe the other way around -> untested ;)
            }
    
            return stringX.Compare(stringY);
        }
    }
    

    Usage:

    _yourListViewControl.CustomSort = new ByLengthAndAlphabeticallyOrderComparer();