反转队列

5

我正在使用扩展方法Reverse(),但好像没有起作用。MSDN表示它是以延迟执行的方式实现的,但是我似乎无法让它正常工作。

以下是我的调用方式:

        Queue<T> currentPath = new Queue<T>();
        currentPath.Enqueue(someValue);
        currentPath.Enqueue(someValue2);

        currentPath.Reverse();

以下是MSDN的翻译:

此方法使用延迟执行实现。立即返回的值是一个对象,它存储执行操作所需的所有信息。由此方法表示的查询不会在直接调用其GetEnumerator方法或在Visual C#中使用foreach或在Visual Basic中使用For Each时枚举对象之前执行。

我不确定调用GetEnumerator是什么意思。我尝试了以下操作,但没有成功:

currentPath.Reverse();
currentPath.GetEnumerator();

我觉得我在这里做了些很傻的事情,需要你的帮助!

这段文字涉及IT技术,因此我对其进行了翻译。请注意,我保留了HTML标签,并且尽力使翻译更加通俗易懂,但不包括解释。
3个回答

18

Reverse返回反转的序列。它不会修改原始序列。可以尝试像这样构建一个新的队列,以将反转的项放入其中:

currentPath = new Queue<T>(currentPath.Reverse());

当文档讲到调用GetEnumerator时,它指的是在Reverse()返回的IEnumerable上调用:
IEnumerable reversed = currentPath.Reverse();
IEnumerator reversedEnumerator = reversed.GetEnumerator();
// Now reversedEnumerator has assembled the reversed sequence,
// we could change the contents of currentPath and it wouldn't
// affect the order of items in reversedEnumerator.

当然,通常情况下我们不需要像这样获取枚举器,因为foreach会在幕后为我们完成它:
IEnumerable reversed = currentPath.Reverse();
foreach (var item in reversed)
{
    // ...
}

实际上,就像我第一个例子中的那样,我们可以将反转的可枚举对象传递给诸如QueueList之类的集合构造函数,并让它执行迭代:

currentPath = new Queue<T>(currentPath.Reverse());

啊,我真是太傻了。我觉得我混淆了,因为当在列表上调用Reverse时,它会修改原始列表(因为Reverse不是List的扩展方法)。谢谢 :) - Benzino

2

Reverse()是Linq操作符。它用于对正在迭代的序列进行操作。因此,您可以执行以下操作:

foreach (var value in currentPath.Reverse())
{
     // Do something
}

这将以相反的顺序迭代队列中的项目。实际的队列保持不变。

您可以像这样创建一个新队列作为现有队列的反向:

var newQueue = new Queue<T>(currentPath.Reverse());

这是我上次检查时使用的LINQ方法。 :) - Bernard
@M.Babcock - 好的,所以这是一个Linq方法和查询运算符。 - Andrew Cooper

1

在调用Reverse()方法后,您尝试过迭代队列吗?

以下是MSDN中的代码:

foreach (T item in currentPath.Reverse())
{
   // Do something with current item in queue.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接