How to make a Sortable ObservableCollection C#

Time ago i had to implement a sortable observable collection that was able to sort its members based on different parameters.
After long and long searching i found this code, and i report it here so it can be useful for readers too.
/*
/*
 * samples:
 * //sort ascending
 * MySortableList.Sort(x => x.Name, ListSortDirection.Ascending);
 *
 * //sort descending
 * MySortableList.Sort(x => x.Name, ListSortDirection.Descending);
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestSortableCollection
{
    public class SortableObservableCollection : ObservableCollection
    {
        public void Sort(Func keySelector, System.ComponentModel.ListSortDirection direction)
        {
            switch (direction)
            {
                case System.ComponentModel.ListSortDirection.Ascending:
                    {
                        ApplySort(Items.OrderBy(keySelector));
                        break;
                    }
                case System.ComponentModel.ListSortDirection.Descending:
                    {
                        ApplySort(Items.OrderByDescending(keySelector));
                        break;
                    }
            }
        }

        public void Sort(Func keySelector, IComparer comparer)
        {
            ApplySort(Items.OrderBy(keySelector, comparer));
        }

        private void ApplySort(IEnumerable sortedItems)
        {
            var sortedItemsList = sortedItems.ToList();

            foreach (var item in sortedItemsList)
            {
                Move(IndexOf(item), sortedItemsList.IndexOf(item));
            }
        }
    }
}


Use it in this way:
public class Person
{
public string Name{get;set;}
public int Age {get;set;}
}

public class PersonCollection:SortableObservableCollection
{
public PersonCollection()
{
[...fill collection...]
this.Sort(x => x.Name, ListSortDirection.Ascending);
}
}

No comments: