Order a ObservableCollection<T> without creating a new one [duplicate]
I have following code to re-order a ObservableCollection<T>
collection:
list = new ObservableCollection<SomeType>( list.OrderBy( c=>c.Ordinal ) );
This code works, but I don't like the fact that "new" is involved. Is there a way I can change the internal element order of a ObservableCollection<T>
collection without creating a new one?
Thanks,
Implement your custom sort extension method for Observable collection
public static class ObservableCollection
{
public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector)
{
List<TSource> sortedList = source.OrderBy(keySelector).ToList();
source.Clear();
foreach (var sortedItem in sortedList)
{
source.Add(sortedItem);
}
}
}
Above answer is inspired by Mr. Jaider's reply to this question
Given that OrderBy
also news up an array to match the size of your collection, and several other objects, you've two choices:
- Give up on LINQ OrderBy altogether and write your own sort that performs in-place sorting over your ObservableCollection using the Move method.
- Wait until the current implementation becomes problematic then apply 1.
Don't worry, newing stuff up isn't so terrible. Linq does it all the time. Unless it's a bottleneck, all is good. Unless there's compelling evidence that sorting in-place will really speed up the show, then there's no problem here.
My answer is inspired by bkk
public static class ObservableCollection
{
public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector, bool isAZ)
{
if (isAZ)
{
List<TSource> sortedList = source.OrderBy(keySelector).ToList();
source.Clear();
foreach (var sortedItem in sortedList)
{
source.Add(sortedItem);
}
}
else
{
List<TSource> sortedList = source.OrderByDescending(keySelector).ToList();
source.Clear();
foreach (var sortedItem in sortedList)
{
source.Add(sortedItem);
}
}
}
}
Usage
_someObservableCollection.Sort(x => x.Number, false); // Where number is an simple property (non-object)
As far as I can tell, ObservableCollection has method for moving items inside the collection. You should get a comparer for your T-type, and then use some sorting algorithm
精彩评论