By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,359 Members | 1,543 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,359 IT Pros & Developers. It's quick & easy.

Can you run a foreach in reverse order?

P: n/a
Is it possible to do something similar to the STL iterators, i.e. to execute
a foreach loop in reverse order?

Thanks,
Fabio
Jan 24 '06 #1
Share this Question
Share on Google+
15 Replies


P: n/a

P: n/a
Fabio,
Is it possible to do something similar to the STL iterators, i.e. to
execute a foreach loop in reverse order?


One could simply reverse the order of the collection before executing the
foreach loop. I know that is a second-best options. However, it will work.

Regards,

Randy
Jan 25 '06 #3

P: n/a
Fabio Cannizzo <fc*****************@london.edu> wrote:
Is it possible to do something similar to the STL iterators, i.e. to execute
a foreach loop in reverse order?


No - and not every iterator would be able to support that behaviour
anyway. Consider a foreach which was based off a stream coming in from
a network - you'd have to wait to find the end of the stream (if that
ever happened) before you could start giving back numbers.

Another example - consider an iterator which yielded prime numbers, in
order. What would a reversed iterator do?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 25 '06 #4

P: n/a
"Jon Skeet [C# MVP]" <sk***@pobox.com> skrev i en meddelelse
news:MP************************@msnews.microsoft.c om...
Fabio Cannizzo <fc*****************@london.edu> wrote:
Is it possible to do something similar to the STL iterators, i.e. to
execute
a foreach loop in reverse order?
Another example - consider an iterator which yielded prime numbers, in
order. What would a reversed iterator do?


Easy - start from the highest prime number, and work downwards. Was it a
trick question?
Jan 25 '06 #5

P: n/a
Peter Kirk wrote:
Another example - consider an iterator which yielded prime numbers, in
order. What would a reversed iterator do?


Easy - start from the highest prime number, and work downwards. Was it a
trick question?


I'm not sure whether you're being sarcastic or not - apologies if you
were joking, just ignore the rest of this post. There *is* no "highest
prime number". Prime numbers have been proved (IIRC) to stretch to
infinity. The iterator would never finish, so there's no end.

Here's a simpler one - an iterator which gives 1, 2, 3, 4 etc using
some "arbitrary length" datatype (like Java's BigInteger). What's the
biggest natural number?

Jon

Jan 25 '06 #6

P: n/a
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Fabio Cannizzo <fc*****************@london.edu> wrote:
Is it possible to do something similar to the STL iterators, i.e. to
execute
a foreach loop in reverse order?


No - and not every iterator would be able to support that behaviour
anyway. Consider a foreach which was based off a stream coming in from
a network - you'd have to wait to find the end of the stream (if that
ever happened) before you could start giving back numbers.


You are right but that is true whether you are programming C# or C++.

In STL an iterator is a pattern not a class. However in practice all reverse
iterators are std::reverse_iterator because this implements reverse
iteration by decorating either a bidirectional or random access iterator
(which is another pattern).

The closest you can get in .NET is a generic wrapper implementing
IEnumerable<T> and taking IList<T> in the constructor (IList<T> would
then be equivalent to a random access iterator in STL)

In practice almost all iterators in C++ that are reversible are random
access rather than merely bidirectional which means that they have array
like properties which means that they would almost certainly implement
IList<T> in C#
Jan 25 '06 #7

P: n/a
"Jon Skeet [C# MVP]" <sk***@pobox.com> skrev i en meddelelse
news:11**********************@z14g2000cwz.googlegr oups.com...
Peter Kirk wrote:
> Another example - consider an iterator which yielded prime numbers, in
> order. What would a reversed iterator do?


Easy - start from the highest prime number, and work downwards. Was it a
trick question?


I'm not sure whether you're being sarcastic or not - apologies if you
were joking,


Ah, sorry, yes it was supposed to be humour.... never did quite get the hang
of that....
Jan 25 '06 #8

P: n/a
> Fabio Cannizzo <fc*****************@london.edu> wrote:
Is it possible to do something similar to the STL iterators, i.e. to
execute a foreach loop in reverse order?

No - and not every iterator would be able to support that behaviour
anyway. Consider a foreach which was based off a stream coming in from
a network - you'd have to wait to find the end of the stream (if that
ever happened) before you could start giving back numbers.

Another example - consider an iterator which yielded prime numbers, in
order. What would a reversed iterator do?


I'm assuming you are talking about something other than executing a foreach
in reverse.

Why wouldn't this work if that's not the case.

[STAThread]
private static void Main()
{
foreach(int i in new ReverseEnumerator(new int[] {1, 2, 3, 4, 5, 6, 7, 8,
9, 10}))
{
Console.Write(i + " ");
}

Console.ReadLine();
}

public class ReverseEnumerator : IEnumerator, IEnumerable
{
private IList enumerable;
private int current = -1;

public ReverseEnumerator(IList enumerable)
{
this.enumerable = enumerable;
current = enumerable.Count;
}

public bool MoveNext()
{
current--;

bool toReturn = enumerable.Count > current && current < enumerable.Count
&& current > -1;

return toReturn;
}

public void Reset()
{
current = enumerable.Count;
}

public object Current
{
get { return enumerable[current]; }
}

public IEnumerator GetEnumerator()
{
return this;
}
}

chris martin
Jan 25 '06 #9

P: n/a
chris martin <chris_m|NOSPAM|@caliber|SPAM|web.com> wrote:
Another example - consider an iterator which yielded prime numbers, in
order. What would a reversed iterator do?


I'm assuming you are talking about something other than executing a foreach
in reverse.

Why wouldn't this work if that's not the case.


Because your code requires that what you want to enumerate implements
IList. Not everything which implements IEnumerator or IEnumerable
implements IList.

<snip>

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 25 '06 #10

P: n/a
Hi John.

I think Peter has a point. In the computer world the concept of infinite
does not exist.
Be it a set, an array or a collection, at any particular point in time it
will have a finite number of elements.

I understand that in C# these do not exists, but I do not agree they do not
make sense. The STL succesfully and conveninetly implement them.

Regards,
Fabio

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Peter Kirk wrote:
> Another example - consider an iterator which yielded prime numbers, in
> order. What would a reversed iterator do?


Easy - start from the highest prime number, and work downwards. Was it a
trick question?


I'm not sure whether you're being sarcastic or not - apologies if you
were joking, just ignore the rest of this post. There *is* no "highest
prime number". Prime numbers have been proved (IIRC) to stretch to
infinity. The iterator would never finish, so there's no end.

Here's a simpler one - an iterator which gives 1, 2, 3, 4 etc using
some "arbitrary length" datatype (like Java's BigInteger). What's the
biggest natural number?

Jon

Jan 25 '06 #11

P: n/a
Fabio Cannizzo <fc*****************@london.edu> wrote:
I think Peter has a point. In the computer world the concept of infinite
does not exist.
It does in my view. When does a random number generator stop? Similarly
a Stream never has to end, but could be iterated over.
Be it a set, an array or a collection, at any particular point in time it
will have a finite number of elements.
However, iterators aren't always over arrays or collections.
I understand that in C# these do not exists, but I do not agree they do not
make sense. The STL succesfully and conveninetly implement them.


So what would it do with the following iterator?

using System;
using System.Collections;
using System.Collections.Generic;

public class RandomIterator : IEnumerable<int>
{
Random rng;

public RandomIterator (int seed)
{
rng = new Random(seed);
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public IEnumerator<int> GetEnumerator()
{
while (true)
{
yield return rng.Next(0, int.MaxValue);
}
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 25 '06 #12

P: n/a
> chris martin <chris_m|NOSPAM|@caliber|SPAM|web.com> wrote:
Another example - consider an iterator which yielded prime numbers,
in order. What would a reversed iterator do?

I'm assuming you are talking about something other than executing a
foreach in reverse.

Why wouldn't this work if that's not the case.

Because your code requires that what you want to enumerate implements
IList. Not everything which implements IEnumerator or IEnumerable
implements IList.

<snip>


Certainly that was a oversight on my part.
Jan 25 '06 #13

P: n/a
You could create a custom enumerator and foreach over that.

--
William Stacey [MVP]

"Fabio Cannizzo" <fc*****************@london.edu> wrote in message
news:iI******************@newsfe4-gui.ntli.net...
| Is it possible to do something similar to the STL iterators, i.e. to
execute
| a foreach loop in reverse order?
|
| Thanks,
| Fabio
|
|
Jan 26 '06 #14

P: n/a

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
chris martin <chris_m|NOSPAM|@caliber|SPAM|web.com> wrote:
> Another example - consider an iterator which yielded prime numbers, in
> order. What would a reversed iterator do?


I'm assuming you are talking about something other than executing a
foreach
in reverse.

Why wouldn't this work if that's not the case.


Because your code requires that what you want to enumerate implements
IList. Not everything which implements IEnumerator or IEnumerable
implements IList.


It is totally possible to write a wrapper that can take IList,IList<T> or
anything (by reflection) that includes appropriate methods/properties (these
would be this[] and Count). You could even allow things having Count and
implementing IEnumerable although it wouldn't be efficient.
Jan 26 '06 #15

P: n/a
Nick Hounsome wrote:
Why wouldn't this work if that's not the case.
Because your code requires that what you want to enumerate implements
IList. Not everything which implements IEnumerator or IEnumerable
implements IList.


It is totally possible to write a wrapper that can take IList,IList<T> or
anything (by reflection) that includes appropriate methods/properties (these
would be this[] and Count).


Absolutely - and Chris's code does indeed cope with IList and would be
easy to change to do IList<T>.
You could even allow things having Count and
implementing IEnumerable although it wouldn't be efficient.


You could certainly do a "buffering" version that went to the end of
the IEnumerable *if* it terminated. It still wouldn't be as flexible as
foreach though, and that's my point - foreach doesn't make any
assumptions about the nature of the iterator, whereas the concept of a
reversible foreach *has* to assume that the iterator has an end.

Jon

Jan 26 '06 #16

This discussion thread is closed

Replies have been disabled for this discussion.