共用方式為


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# 或 Visual Basic 中使用 foreach 來列舉對象,否則 For Each 不會執行這個方法所表示的查詢。

適用於