Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order a ObservableCollection<T> without creating a new one [duplicate]

Tags:

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,

like image 530
sean717 Avatar asked Oct 19 '10 21:10

sean717


2 Answers

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

like image 190
bkk Avatar answered Sep 29 '22 18:09

bkk


Given that OrderBy also news up an array to match the size of your collection, and several other objects, you've two choices:

  1. Give up on LINQ OrderBy altogether and write your own sort that performs in-place sorting over your ObservableCollection using the Move method.
  2. 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.

like image 27
spender Avatar answered Sep 29 '22 20:09

spender