sooprise
sooprise

Reputation: 23187

Changing Foreach Order?

Is there anyway to foreach through a list from the end to the beginning rather than the beginning to then end (preferably without reordering the list).

Upvotes: 13

Views: 19807

Answers (8)

Jgonzalez731
Jgonzalez731

Reputation: 353

You can construct your list as a stack and then iterate over the stack:

Stack<char> stack = new Stack<char>();

//Add items...
        
foreach(var item in stack)
{
    ...
}

Upvotes: 0

Tiju John
Tiju John

Reputation: 1180

IList<String> strList = new IList<String>();
strList.Add("A");
strList.Add("B");
strList.Add("C");

for (int i = strList.Count-1; i>=0;i--)
{
    Console.WriteLine(strList[i]);
}

not tried but should work.

Upvotes: 1

Bryan Watts
Bryan Watts

Reputation: 45445

using System.Linq;

foreach(var item in source.Reverse())
{
    ...
}

Edit: There is one more step if you are dealing specifically with a List<T>. That class defines its own Reverse method whose signature is not the same as the Enumerable.Reverse extension method. In that case, you need to "lift" the variable reference to IEnumerable<T>:

using System.Linq;

foreach(var item in list.AsEnumerable().Reverse())
{
    ...
}

Upvotes: 44

Jorge Ferreira
Jorge Ferreira

Reputation: 97849

Error checking ommitted for clarity. Use a custom implementation of IEnumerable and IEnumerator. This will avoid unnecessary copying.

using System;
using System.Collections.Generic;

namespace ConsoleApplication3
{
    class ReversedEnumerator : IEnumerator<int>
    {
        List<int> v;
        int index;

        public ReversedEnumerator(List<int> v) {
            this.v = v;
            this.index = v.Count;
        }

        public int Current
        {
            get { return v[index]; }
        }

        public void Dispose()
        {
        }

        object System.Collections.IEnumerator.Current
        {
            get { return v[index]; }
        }

        public bool MoveNext()
        {
            return --index >= 0;
        }

        public void Reset()
        {
            index = this.v.Count;
        }
    }

    class EnumeratorStub : IEnumerable<int>
    {
        List<int> v;

        public EnumeratorStub(List<int> v)
        {
            this.v = v;
        }

        public IEnumerator<int> GetEnumerator()
        {
            return new ReversedEnumerator(v);
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return new ReversedEnumerator(v);
        }

    }

    class Program
    {
        static EnumeratorStub Reverse(List<int> v)
        {
            return new EnumeratorStub(v);
        }

        static void Main(string[] args)
        {
            List<int> v = new List<int>();
            v.Add(1);
            v.Add(2);
            v.Add(3);

            foreach (int item in Reverse(v))
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}

I would recommend to refactor the code sample to use generics. That way you could use this for any container type.

Upvotes: 1

Andrey Taptunov
Andrey Taptunov

Reputation: 9495

It depends on what you mean by list.

  • List<T> ? No, unless you use Linq and it's Reverse() function.
  • Your custom collection? Easily, just implement IEnumerator like you want.

Upvotes: 2

Fredou
Fredou

Reputation: 20100

not c# but you can do it too :-)

    Dim a As New List(Of Integer)
    a.Add(1)
    a.Add(2)
    a.Add(3)

    For Each i In a.AsEnumerable.Reverse
        Debug.Print(i)

    Next

Upvotes: 0

womp
womp

Reputation: 116977

You probably don't want to do anything complicated, so I would suggest just using a for loop.

However, if it were somehow a requirement, you can certainly implement your own iterators for custom list iteration behavior.

Upvotes: 3

Jim
Jim

Reputation: 3665

you could use a regular for loop, start at the end and decrement, instead of starting at the top and incrementing.

something like:

for(int i=foo.lenth; i != 0; i--)
{
do stuff
}

Upvotes: 10

Related Questions