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

前端 未结 5 821
北恋
北恋 2021-02-03 17:40

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         


        
相关标签:
5条回答
  • 2021-02-03 18:06
    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]
    
    0 讨论(0)
  • 2021-02-03 18:07

    You're looking for the Enumerable.Range method:

    var mySequence = Enumerable.Range(0, 12);
    
    0 讨论(0)
  • 2021-02-03 18:11

    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).

    0 讨论(0)
  • 2021-02-03 18:17
    Enumerable.Range(start, numElements);
    
    0 讨论(0)
  • 2021-02-03 18:21

    Enumerable.Range(0,12);

    0 讨论(0)
提交回复
热议问题