It would be impossible to implement a reverse foreach as a language
construct (without much overhead), because foreach relies on the IEnumerable
interface, which is supposed to return elements sequentially from start to
end. But in 2.0 you can easily implement a reverse enumerator for objects
implementing IList, like:
class ReverseEnum : IEnumerable
{
IList list;
public RevereseEnum(IList list)
{
this.list = list;
}
IEnumerator GetEnumerator()
{
for (int index = list.Count - 1; index >= 0; index--)
yield return list[index];
}
}
and use it like:
foreach (object o in new RevereseEnum(msgqueue.ToArray()))
{
...
}
HTH,
Stefan
"Sagaert Johan" <RE*************@hotmail.com> wrote in message
news:OY**************@TK2MSFTNGP14.phx.gbl...
Hi
Is this something for C# V2 ?
Queue msgqueue =new Queue ();
//fill some data in the queue here with this function & keep only the last
5
events
void addtolog(string msg)
{
msgqueue.Enqueue(msg);
if (msgqueue.Count>5)
msgqueue.Dequeue();
}
// print contents of queue without dequeing the data.
foreach (object o in msgqueue )
{
Console.WriteLine((string)o);
}
// printing in reverse :
object[] items=msgqueue.ToArray();
for (int i=items.Length;i>0;i-- )
{
Console.WriteLine((string)items[i-1]);
}
Johan