views:

104

answers:

2

Going from Rails to ASP.net has been quite a pain. But I was wondering if any gurus out there know of equivalent translation of "cycle" from Rails for ASP.net ?

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001721

Basically to be able to conditionally output the nth parameter based on the nth time it's called.

Many thanks!

A: 

There's no built-in function to accomplish that - you will have to code it yourself. You can accomplish the same thing using modulo, but you will have to use a for loop (or some kind of index):

var colours = new List {"Red", "Green", "Blue"};

for (int i=0; i < rows.length; i++) {
    out.write("<p class='" + colours[i % colours.Count] + "'>" + rows[i].Name + "</p>");
}

Now, I'm sure you will agree that this is much more elegant than that silly Ruby stuff ;-)

Travis
A: 

You could roll your own using the yield keyword. Here's something that'll give you similar functionality. You'll need to include this namespace to make use of the IEnumerable interface:

using System.Collections;

Here's an example:

public static void Main()
{
    string[] myColors = { "red", "green", "blue" };
    // this would be your external loop, such as the one building up the table in the RoR example
    for (int index = 0; index < 3; index++)
    {
     foreach (string color in Cycle(myColors))
     {
      Console.WriteLine("Current color: {0}", color);
     }
    }
}

public static IEnumerable Cycle<T>(T[] items)
{
    foreach (T item in items)
    {
     yield return item;
    }
}

The Cycle method uses generics in the code sample above to allow the use of other types. For example, where myColors is declared you could use:

int[] myInts = { 0, 1, 2, 3 };
bool[] myBools = { true, false };

And in the loop you could have:

foreach (int i in Cycle(myInts))
{
    Console.WriteLine("Current int: {0}", i);
}
foreach (bool b in Cycle(myBools))
{
    Console.WriteLine("Current bool: {0}", b);
}
Ahmad Mageed
Superb. Many thanks, sir.
eusden