在 C# 中是否有等效的 Python 范围(12)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1271378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:49:58  来源:igfitidea点击:

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

c#pythonrangexrange

提问by Daren Thomas

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

这对我来说时不时会出现:我有一些 C# 代码非常想要range()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.

但这在功能使用中会出现问题,因为当我想要执行 LinqSum()而不是编写上述循环时。

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

有内置的吗?我想我可以永远只是推出自己用yield还是这样,但是这将是如此得心应手,只是

回答by LukeH

You're looking for the Enumerable.Rangemethod:

您正在寻找Enumerable.Range方法:

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

回答by TimY

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.

只是为了补充每个人的答案,我想我应该补充说它Enumerable.Range(0, 12);更接近 Python 2.x,xrange(12)因为它是一个可枚举的。

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

更接近 Python 的range(12).

回答by Mark Rushakoff

Enumerable.Range(start, numElements);

回答by Mel Gerats

Enumerable.Range(0,12);

Enumerable.Range(0,12);

回答by Jabba

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]