1

I want to reverse the order of items in an observable collection. This is my sample code:

        int[] collection1 = new int[] { 1, 2, 3, 4, 5 };
        ObservableCollection<int> obColl1 = new ObservableCollection<int>();
        foreach ( var item in collection1 ) // initial order 1,2,3,4,5
        {
            obColl1.Add(item);
            Console.WriteLine("Added {0} in ObservableCollection", item);
        }
        Console.WriteLine("Now reverse their order");

        obColl1.Reverse();
        foreach ( var item in obColl1 ) // still show 1,2,3,4,5 instead of 5,4,3,2,1
        {
            Console.WriteLine("After reversing ObservableCollection: {0}", item);
        }

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();

The output result shows still the same order as initial order. Am I missing something? some mistakes?

Thank you in advance

4

2 回答 2

3

您需要重新分配它:

obColl1 = new ObservableCollection<int>(obColl1.Reverse());
于 2013-07-25T11:10:27.927 回答
2

您需要将返回值分配给一个对象

就像是

int[] collection1 = new int[] { 1, 2, 3, 4, 5 };
ObservableCollection<int> obColl1 = new ObservableCollection<int>();
foreach (var item in collection1) // initial order 1,2,3,4,5
{
    obColl1.Add(item);
    Console.WriteLine("Added {0} in ObservableCollection", item);
}
Console.WriteLine("Now reverse their order");

var ret = obColl1.Reverse(); //try the changes here and the line below.
foreach (var item in ret) // still show 1,2,3,4,5 instead of 5,4,3,2,1
{
    Console.WriteLine("After reversing ObservableCollection: {0}", item);
}

Console.WriteLine("Press any key to exit");
Console.ReadKey();

Enumerable.Reverse 方法中,您将看到它具有返回类型,因此您需要将其分配给对象。

于 2013-07-25T10:59:11.873 回答