Enumerable.Range(Int32, Int32) 方法

定义

生成指定范围内的整数的序列。Generates a sequence of integral numbers within a specified range.

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

序列中第一个整数的值。The value of the first integer in the sequence.

count
Int32

要生成的顺序整数的数目。The number of sequential integers to generate.

返回

C# 中的 IEnumerable<Int32> 或 Visual Basic 中的 IEnumerable(Of Int32),其中包含某个范围的顺序整数。An IEnumerable<Int32> in C# or IEnumerable(Of Int32) in Visual Basic that contains a range of sequential integral numbers.

异常

count 小于 0。count is less than 0.

-or- start + count -1 大于 MaxValuestart + count -1 is larger than MaxValue.

示例

下面的代码示例演示如何使用 Range 生成一个值序列。The following code example demonstrates how to use Range to generate a sequence of values.

// 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

注解

此方法是使用延迟执行实现的。This method is implemented by using deferred execution. 即时返回值是一个对象,该对象存储执行操作所需的所有信息。The immediate return value is an object that stores all the information that is required to perform the action. 此方法表示的查询在枚举对象之前不会执行,方法是通过直接调用 GetEnumerator 方法或在 Visual Basic 中使用视觉C#对象中的 foreachFor Each 来枚举对象。The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

适用于