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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With