如何在 C# 中创建整数序列?

发布于 2024-10-10 08:06:55 字数 121 浏览 6 评论 0原文

F# 具有允许创建序列的序列

seq { 0 .. 10 }

创建从 0 到 10 的数字序列。C

# 中有类似的东西吗?

F# has sequences that allows to create sequences:

seq { 0 .. 10 }

Create sequence of numbers from 0 to 10.

Is there something similar in C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

∞琼窗梦回ˉ 2024-10-17 08:06:55

您可以使用Enumerable.Range(0, 10);。示例:

var seq = Enumerable.Range(0, 10);

MSDN 页面此处

You can use Enumerable.Range(0, 10);. Example:

var seq = Enumerable.Range(0, 10);

MSDN page here.

柠北森屋 2024-10-17 08:06:55
Enumerable.Range(0, 11);

生成指定范围内的整数序列。

http://msdn.microsoft.com/en-us /library/system.linq.enumerable.range.aspx

Enumerable.Range(0, 11);

Generates a sequence of integral numbers within a specified range.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx

强者自强 2024-10-17 08:06:55

您可以创建一个简单的函数。这适用于更复杂的序列。否则 Enumerable.Range 应该可以。

IEnumerable<int> Sequence(int n1, int n2)
{
    while (n1 <= n2)
    {
        yield return  n1++;
    }
}

You could create a simple function. This would work for a more complicated sequence. Otherwise the Enumerable.Range should do.

IEnumerable<int> Sequence(int n1, int n2)
{
    while (n1 <= n2)
    {
        yield return  n1++;
    }
}
北城挽邺 2024-10-17 08:06:55

Linq 投影与很少使用的 索引器重载 (i)

(new int[11]).Select((o,i) => i)

我更喜欢这种方法,因为它的灵活性。

例如,如果我想要偶数:

(new int[11]).Select((item,i) => i*2)

或者如果我想要一小时 5 分钟增量:

(new int[12]).Select((item,i) => i*5)

或者字符串:

(new int[12]).Select((item,i) => "Minute:" + i*5)

Linq projection with the rarely used indexer overload (i):

(new int[11]).Select((o,i) => i)

I prefer this method for its flexibilty.

For example, if I want evens:

(new int[11]).Select((item,i) => i*2)

Or if I want 5 minute increments of an hour:

(new int[12]).Select((item,i) => i*5)

Or strings:

(new int[12]).Select((item,i) => "Minute:" + i*5)
夏至、离别 2024-10-17 08:06:55

在 C# 8.0 中,您可以使用 索引和范围

例如:

var seq = 0..2;
var array = new string[]
{
    "First",
    "Second",
    "Third",
};

foreach(var s in array[seq])
{
    System.Console.WriteLine(s);
}
// Output: First, Second

或者如果您想创建IEnumerable,那么您可以使用扩展名:

public static IEnumerable<int> ToEnumerable(this Range range)
{
   for (var i = range.Start.Value; i < range.End.Value; i++)
   {
       yield return i;
   }
}
...
var seq = 0..2;

foreach (var s in seq.ToEnumerable())
{
   System.Console.WriteLine(s);
}
// Output: 0, 1

PS 但要小心'indexes from end'。例如,ToEnumerable 扩展方法不适用于 var seq = ^2..^0

In C# 8.0 you can use Indices and ranges

For example:

var seq = 0..2;
var array = new string[]
{
    "First",
    "Second",
    "Third",
};

foreach(var s in array[seq])
{
    System.Console.WriteLine(s);
}
// Output: First, Second

Or if you want create IEnumerable<int> then you can use extension:

public static IEnumerable<int> ToEnumerable(this Range range)
{
   for (var i = range.Start.Value; i < range.End.Value; i++)
   {
       yield return i;
   }
}
...
var seq = 0..2;

foreach (var s in seq.ToEnumerable())
{
   System.Console.WriteLine(s);
}
// Output: 0, 1

P.S. But be careful with 'indexes from end'. For example, ToEnumerable extension method is not working with var seq = ^2..^0.

你在我安 2024-10-17 08:06:55

我的实现:

    private static IEnumerable<int> Sequence(int start, int end)
    {
        switch (Math.Sign(end - start))
        {
            case -1:
                while (start >= end)
                {
                    yield return start--;
                }

                break;

            case 1:
                while (start <= end)
                {
                    yield return start++;
                }

                break;

            default:
                yield break;
        }
    }

My implementation:

    private static IEnumerable<int> Sequence(int start, int end)
    {
        switch (Math.Sign(end - start))
        {
            case -1:
                while (start >= end)
                {
                    yield return start--;
                }

                break;

            case 1:
                while (start <= end)
                {
                    yield return start++;
                }

                break;

            default:
                yield break;
        }
    }
池木 2024-10-17 08:06:55

最初在这里回答


如果您想枚举从 010 的数字序列 (IEnumerable),请尝试

Enumerable.Range(0, ++10);

在解释中获取从 0 到 10 的数字序列,您希望该序列从 0 开始(请记住,0 到 10 之间有 11 个数字)。


如果您想要一个无限的线性系列,您可以编写一个类似的函数

IEnumerable<int> Series(int k = 0, int n = 1, int c = 1)
{
    while (true)
    {
        yield return k;
        k = (c * k) + n;
    }
}

,您可以使用类似的

var ZeroTo10 = Series().Take(11);

函数,如果您想要一个可以重复调用以生成递增数字的函数,也许您想要类似的东西。

using System.Threading;

private static int orderNumber = 0;

int Seq()
{
    return Interlocked.Increment(ref orderNumber);
}

当您调用 Seq() 时,它将返回下一个订单号并递增计数器。

Originally answered here.


If you want to enumerate a sequence of numbers (IEnumerable<int>) from 0 to a 10, then try

Enumerable.Range(0, ++10);

In explanation, to get a sequence of numbers from 0 to 10, you want the sequence to start at 0 (remembering that there are 11 numbers between 0 and 10, inclusive).


If you want an unlimited linear series, you could write a function like

IEnumerable<int> Series(int k = 0, int n = 1, int c = 1)
{
    while (true)
    {
        yield return k;
        k = (c * k) + n;
    }
}

which you could use like

var ZeroTo10 = Series().Take(11);

If you want a function you can call repeatedly to generate incrementing numbers, perhaps you want somthing like.

using System.Threading;

private static int orderNumber = 0;

int Seq()
{
    return Interlocked.Increment(ref orderNumber);
}

When you call Seq() it will return the next order number and increment the counter.

゛清羽墨安 2024-10-17 08:06:55

我的代码中有这些函数

private static IEnumerable<int> FromZero(this int count)
    {
        if (count <= 0)
            yield break;

        for (var i = 0; i < count; i++)
        {
            yield return i;
        }
    }

    private static IEnumerable<int> FromOne(this int count)
    {
        if (count <= 0)
            yield break;

        for (var i = 1; i <= count; i++)
        {
            yield return i;
        }
    }

这有助于减少一些 for(i) 代码。

I have these functions in my code

private static IEnumerable<int> FromZero(this int count)
    {
        if (count <= 0)
            yield break;

        for (var i = 0; i < count; i++)
        {
            yield return i;
        }
    }

    private static IEnumerable<int> FromOne(this int count)
    {
        if (count <= 0)
            yield break;

        for (var i = 1; i <= count; i++)
        {
            yield return i;
        }
    }

This helps to reduce some for(i) code.

人生戏 2024-10-17 08:06:55

如果您还希望将生成的序列保存在变量中:

using System.Collections.Generic;
using System.Linq;

IEnumerable<int> numbersToPrint = Enumerable.Range(1, 11);

这在上面显示的其他解决方案中是隐式的,但我还显式地包含了所需的命名空间,以便使其按预期工作。

In case you wish to also save the generated sequence in a variable:

using System.Collections.Generic;
using System.Linq;

IEnumerable<int> numbersToPrint = Enumerable.Range(1, 11);

This is implicit in other solutions shown above, but I am also explicitly including the needed namespaces for this to work as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文