ASP.net equivalent of Rails "loop"?

The transition from Rails to ASP.net was quite painful. But I was wondering if any gurus know an equivalent translation of the Rails "loop" for ASP.net?

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

Basically, to be able to conditionally output the n-th parameter based on the n-th time it called.

Many thanks!

0


a source to share


2 answers


You can roll your own using the yield keyword . Here's something that will give you similar functionality. You will need to include this namespace in order to use 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 sample loop uses generics in the sample code to allow other types to be used. For example, if myColors is declared, you can use:

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

      

And in a loop, you could:

foreach (int i in Cycle(myInts))
{
    Console.WriteLine("Current int: {0}", i);
}
foreach (bool b in Cycle(myBools))
{
    Console.WriteLine("Current bool: {0}", b);
}

      

0


a source


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

var colors = 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 this silly Ruby stuff; -)

0


a source







All Articles