2012-03-11 116 views
2

我正在使用扩展menthod 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(); 

我感觉我做的东西很无聊的在这里,任何帮助,将不胜感激!

回答

11

反向返回反向序列。它不会修改原文。尝试这样的事情,建立一个新的队列走出逆转项目:

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

当有关调用的GetEnumerator文档会谈,就意味着对被反向()返回了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()); 
+0

啊,怎么我傻的。我想我很困惑,因为当在列表上调用Reverse时,它会修改原始内容(因为Reverse不是List的扩展方法)。谢谢:) – Benzino 2012-03-12 00:11:32

2

Reverse()是一个LINQ操作。它用于按照您正在进行交易的序列进行操作。所以你可以做这样的事情:

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

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

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

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

'Reverse'是一个运营商? – 2012-03-12 00:00:55

+0

这是我上次检查时的LINQ方法。 :) – Bernard 2012-03-12 00:02:12

+0

@ M.Babcock - 好的,所以它是一个Linq方法和一个查询操作符。 – 2012-03-12 00:19:04

1

你有没有打过电话的Reverse()方法后遍历队列?

这里是MSDN是说在代码:

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