![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class SortableObservableCollection<T> : ObservableCollection<T>
2 {
3 public SortableObservableCollection(List<T> list)
4 : base(list)
5 {
6 }
7
8 public SortableObservableCollection(IEnumerable<T> collection)
9 : base(collection)
10 {
11 }
12
13 public void Sort<TKey>(Func<T, TKey> keySelector, System.ComponentModel.ListSortDirection direction)
14 {
15 switch (direction)
16 {
17 case System.ComponentModel.ListSortDirection.Ascending:
18 {
19 ApplySort(Items.OrderBy(keySelector));
20 break;
21 }
22 case System.ComponentModel.ListSortDirection.Descending:
23 {
24 ApplySort(Items.OrderByDescending(keySelector));
25 break;
26 }
27 }
28 }
29
30 public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
31 {
32 ApplySort(Items.OrderBy(keySelector, comparer));
33 }
34
35 private void ApplySort(IEnumerable<T> sortedItems)
36 {
37 var sortedItemsList = sortedItems.ToList();
38
39 foreach (var item in sortedItemsList)
40 {
41 Move(IndexOf(item), sortedItemsList.IndexOf(item));
42 }
43 }
44 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary>
2 /// DESCRIPTION
3 /// </summary>
4 public class SortableObservableCollection<T> : ObservableCollection<T>
5 {
6 private bool sorting;
7
8 public void Sort()
9 {
10 this.Sort(Comparer<T>.Default);
11 }
12
13 public void Sort(IComparer<T> comparer)
14 {
15 this.sorting = true;
16
17 int i, j;
18 for (i = 1; i < this.Count; i++)
19 {
20 T index = this[i];
21 j = i;
22 while ((j > 0) && (comparer.Compare(this[j - 1], index) == 1))
23 {
24 this[j] = this[j - 1];
25 j = j - 1;
26 }
27 this[j] = index;
28 }
29
30 this.sorting = false;
31
32 this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
33 }
34
35 protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
36 {
37 if (this.sorting == false)
38 {
39 base.OnCollectionChanged(e);
40 }
41 }
42 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary>
2 /// Create a instance of SortableObservableCollection.
3 /// </summary>
4 /// <typeparam name="T">Collection</typeparam>
5 public class SortableObservableCollection<T> : ObservableCollection<T>
6 {
7 public virtual void Sort()
8 {
9 this.Sort(0, Count, null);
10 }
11
12 public virtual void Sort(IComparer<T> comparer)
13 {
14 this.Sort(0, Count, comparer);
15 }
16
17 public virtual void Sort(int index, int count, IComparer<T> comparer)
18 {
19 (this.Items as List<T>).Sort(index, count, comparer);
20 OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
21 }
22 }