¿Hay un equivalente del rango de pitones (12) en C#?


Esto surge de vez en cuando para mí: tengo algún código de C# que desea mal la función range() disponible en Python.

Soy consciente de usar

for (int i = 0; i < 12; i++)
{
   // add code here
}

Pero esto frena en usos funcionales, como cuando quiero hacer un Linq Sum() en lugar de escribir el bucle anterior.

¿Hay alguno construido? Supongo que siempre podría rodar el mío con un yield o tal, pero esto sería tan útil para solo tener.

Author: yuvalm2, 2009-08-13

5 answers

Usted está buscando el Enumerable.Range método:

var mySequence = Enumerable.Range(0, 12);
 76
Author: LukeH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-13 11:30:42

Solo para complementar las respuestas de todos, pensé que debería agregar que Enumerable.Range(0, 12); está más cerca de Python 2.x xrange(12) porque es un enumerable.

Si alguien requiere específicamente una lista o una matriz:

Enumerable.Range(0, 12).ToList();

O

Enumerable.Range(0, 12).ToArray();

Están más cerca de los range(12) de Python.

 14
Author: TimY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-28 17:36:48
Enumerable.Range(start, numElements);
 7
Author: Mark Rushakoff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-08 01:42:15

Enumerable.Intervalo (0,12);

 5
Author: Mel Gerats,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-13 11:25:53
namespace CustomExtensions
{
    public static class Py
    {
        // make a range over [start..end) , where end is NOT included (exclusive)
        public static IEnumerable<int> RangeExcl(int start, int end)
        {
            if (end <= start) return Enumerable.Empty<int>();
            // else
            return Enumerable.Range(start, end - start);
        }

        // make a range over [start..end] , where end IS included (inclusive)
        public static IEnumerable<int> RangeIncl(int start, int end)
        {
            return RangeExcl(start, end + 1);
        }
    } // end class Py
}

Uso:

using CustomExtensions;

Py.RangeExcl(12, 18);    // [12, 13, 14, 15, 16, 17]

Py.RangeIncl(12, 18);    // [12, 13, 14, 15, 16, 17, 18]
 0
Author: Jabba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 14:19:36