Is there an equivalent of Pythons range(12) in C#?

C#PythonRangeXrange

C# Problem Overview


This crops up every now and then for me: I have some C# code badly wanting the range() function available in Python.

I am aware of using

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

But this brakes down in functional usages, as when I want to do a Linq Sum() instead of writing the above loop.

Is there any builtin? I guess I could always just roll my own with a yield or such, but this would be so handy to just have.

C# Solutions


Solution 1 - C#

You're looking for the Enumerable.Range method:

var mySequence = Enumerable.Range(0, 12);

Solution 2 - C#

Just to complement everyone's answers, I thought I should add that Enumerable.Range(0, 12); is closer to Python 2.x's xrange(12) because it's an enumerable.

If anyone requires specifically a list or an array:

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

or

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

are closer to Python's range(12).

Solution 3 - C#

Enumerable.Range(start, numElements);

Solution 4 - C#

Enumerable.Range(0,12);

Solution 5 - C#

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
}

Usage:

using CustomExtensions;

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaren ThomasView Question on Stackoverflow
Solution 1 - C#LukeHView Answer on Stackoverflow
Solution 2 - C#TimYView Answer on Stackoverflow
Solution 3 - C#Mark RushakoffView Answer on Stackoverflow
Solution 4 - C#Mel GeratsView Answer on Stackoverflow
Solution 5 - C#JabbaView Answer on Stackoverflow