foreach in reverse direction ? feature for C# V2 ?

S

Sagaert Johan

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
 
A

Anders Borum [.NET/C# MCP]

Hello!

You could do this with a custom built enumerator. For instance, by
implementing the IEnumerable interface and using the "yield return" keywords
in a reverse loop.

public IEnumerable QueueList
{
object[] items = msgqueue.ToArray();

for (int i = items.Length; i > 0; i--)
{
yield return (string) items[i - 1];
}
}

btw. above is a snippet of code I wrote quickly.. just to illustrate!
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

AFAIK there is nothing like that in C# 2.0 if you need it you could use
several workarounds , like using a stack

Stack stack = new Stack ( Queue )

then you can use Pop to get a reverse collection.


Cheers,
 
S

Stefan Simek

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
 
A

Anders Borum [.NET/C# MCP]

That should have been:

public IEnumerator QueueList instead of
public IEnumerable QueueList.

I'm sorry.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top