Enumerable.Repeat<TResult>(TResult, Int32) 方法

定义

生成包含一个重复值的序列。

public:
generic <typename TResult>
 static System::Collections::Generic::IEnumerable<TResult> ^ Repeat(TResult element, int count);
public static System.Collections.Generic.IEnumerable<TResult> Repeat<TResult> (TResult element, int count);
static member Repeat : 'Result * int -> seq<'Result>
Public Function Repeat(Of TResult) (element As TResult, count As Integer) As IEnumerable(Of TResult)

类型参数

TResult

要在结果序列中重复的值的类型。

参数

element
TResult

要重复的值。

count
Int32

在生成序列中重复该值的次数。

返回

IEnumerable<TResult>

一个包含重复值的 IEnumerable<T>

例外

count 小于 0。

示例

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

IEnumerable<string> strings =
    Enumerable.Repeat("I like programming.", 15);

foreach (String str in strings)
{
    Console.WriteLine(str);
}

/*
 This code produces the following output:

 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
*/
' Repeat the same string to create a sequence.
Dim sentences As IEnumerable(Of String) =
Enumerable.Repeat("I like programming.", 15)

Dim output As New System.Text.StringBuilder
For Each sentence As String In sentences
    output.AppendLine(sentence)
Next

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

' This code produces the following output:
'
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.
' I like programming.

注解

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

适用于