简体   繁体   中英

C#: Linq Reverse Collection failed

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

您需要重新分配它:

obColl1 = new ObservableCollection<int>(obColl1.Reverse());

You need to assign the return value to an object

Something like

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();

From Enumerable.Reverse Method you will see that it has a return type, so you need to assign that to an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM