C#:Linq Reverse Collection失败了

时间:2013-07-25 10:54:47

标签: linq c#-4.0 collections reverse

我想颠倒可观察集合中项目的顺序。 这是我的示例代码:

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

输出结果显示与初始订单仍然相同的顺序。我错过了什么吗?一些错误?

提前谢谢

2 个答案:

答案 0 :(得分:3)

你需要重新分配它:

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

答案 1 :(得分: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 Method 你会看到它有一个返回类型,所以你需要将它分配给一个对象。