7

This one should be easy, and im ashamed i havent figured it out myself yet. I'm trying to reverse the order of a list of items in my wp7 app. The list is an ObservableCollection. When using system.linq, intellisense lets me do this: myList.Reverse(); ,but this doesnt seem to work. Am i doing something wrong, or is there some other way i can do this easily?

Thanks in advance.

  • 3
    "Doesn't seem to work", how? Do you mean the UI doesn't show the items in reversed order? – user7116 Jul 10 '12 at 22:17
  • Related question, but not necessarily a duplicate http://stackoverflow.com/questions/10413535/reverse-order-of-observablecollection – user7116 Jul 10 '12 at 22:22

3 Answers3

34

Reverse returns an IEnumerable, it does not modify the collection. To modify the collection you could do

collection = new ObservableCollection<YourType>(collection.Reverse());
Shawn Kendrot
  • 12,425
  • 1
  • 25
  • 41
4

If you don't want to recreate the collection:

for (int i = 0; i < collection.Count; i++)
  collection.Move(collection.Count - 1, i);
Maxence
  • 12,868
  • 5
  • 57
  • 69
0

make a class that inherits the observablecollection(of T) and implement a sort object in it. This is a vb.net brute force way of doing that:

    Public Sub Sort(ByVal comparer As IComparer(Of T))
    Dim j As Integer
    Dim index As T
    For i As Integer = 1 To Count - 1
        index = Me(i)
        j = i
        While (j > 0) AndAlso (comparer.Compare(Me(j - 1), index) = 1)
            Me(j) = Me(j - 1)
            j = j - 1
        End While
        Me(j) = index
    Next
End Sub
Phil
  • 1,852
  • 2
  • 28
  • 55