Enumerable.Range(Int32, Int32) 方法

定义

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

public:
 static System::Collections::Generic::IEnumerable<int> ^ Range(int start, int count);
public static System.Collections.Generic.IEnumerable<int> Range (int start, int count);
static member Range : int * int -> seq<int>
Public Function Range (start As Integer, count As Integer) As IEnumerable(Of Integer)

参数

start
Int32

序列中第一个整数的值。

count
Int32

要生成的顺序整数的数目。

返回

IEnumerable<Int32> C# 或 IEnumerable(Of Int32) Visual Basic 中包含一系列顺序整型数的 。

例外

count 小于 0。

start + count -1 大于 Int32.MaxValue

示例

下面的代码示例演示如何使用 Range 生成值序列。

// Generate a sequence of integers from 1 to 10
// and then select their squares.
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);

foreach (int num in squares)
{
    Console.WriteLine(num);
}

/*
 This code produces the following output:

 1
 4
 9
 16
 25
 36
 49
 64
 81
 100
*/
' Generate a sequence of integers from 1 to 10
' and project their squares.
Dim squares As IEnumerable(Of Integer) =
Enumerable.Range(1, 10).Select(Function(x) x * x)

Dim output As New System.Text.StringBuilder
For Each num As Integer In squares
    output.AppendLine(num)
Next

' Display the output.
Console.WriteLine(output.ToString())

' This code produces the following output:
'
' 1
' 4
' 9
' 16
' 25
' 36
' 49
' 64
' 81
' 100

注解

此方法通过使用延迟执行来实现。 即时返回值是一个对象,用于存储执行操作所需的所有信息。 在通过直接调用GetEnumerator其方法或在 C# For Eachforeach Visual Basic 中使用 来枚举对象之前,不会执行此方法表示的查询。

适用于