Wednesday, June 22, 2011

WPF - C# Sorting ObservableCollection

After searching the web I found a lot of examples for sorting an ObservableCollection when using custom objects but none with a basic string. So here is what I did:

Having:

ObservableCollection list


Implementing the following method into a static type class:

///
/// Sorts the given list by ascending value.
///

///
public static void BubbleSort(this IList o)
{
for (int i = o.Count - 1; i >= 0; i--)
{
for (int j = 1; j <= i; j++) { object o1 = o[j - 1]; object o2 = o[j]; if (((IComparable)o1).CompareTo(o2) > 0)
{
o.Remove(o1);
o.Insert(j, o1);
}
}
}
}


Calling by using .BubbleSort(list).

The result is the list ordered by ascending value.

Reference: The Sandpit



No comments: