开发者

foreach inversly

Is there posible way to make foreach iterate through the collecti开发者_JS百科on from the end to the begining?

int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
    foreach (int i in fibarray)
    {
        System.Console.WriteLine(i);
    }

How to display inversly with foreach ?


using System.Linq;

foreach (int i in fibArray.Reverse())

But a normal for loop will be more efficient:

for( int index = fibArray.Length - 1; index >= 0; --index ) {
    int i = fibArray[index];
    ...
}


You could use Reverse():

int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray.Reverse())
{
    System.Console.WriteLine(i);
}

In general foreach must support any IEnumerable which only support forward enumeration of items in the collection, as an alternative to Reverse() you could write your own optimized implementation that works on an IList which provides an indexer.


foreach (int i in fibarray.Reverse<int>())
{
    System.Console.WriteLine(i);
}


Nope. Use for instead, or modify your collection to be in the desired order before iterating.


Enumerable.Reverse()

foreach (int i in fibarray.Reverse)
    System.Console.Writeline(i);


I don't think this is possible by default. You would need to create your own class with an iterator with that capability:

C# .NET Iterator Example : Reverse Iteration


In short, no. You cannot change the behavior of foreach. If you want to do this without returning a new array (like calling Reverse), then use a for loop.

int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
for (int i = fibarray.Length - 1; i > -1; i--) {
    Console.WriteLine(i);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜