Enumerable.Prepend<TSource>(IEnumerable<TSource>, TSource) 方法
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將值新增至序列的開頭。
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static System::Collections::Generic::IEnumerable<TSource> ^ Prepend(System::Collections::Generic::IEnumerable<TSource> ^ source, TSource element);
C#
public static System.Collections.Generic.IEnumerable<TSource> Prepend<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, TSource element);
static member Prepend : seq<'Source> * 'Source -> seq<'Source>
<Extension()>
Public Function Prepend(Of TSource) (source As IEnumerable(Of TSource), element As TSource) As IEnumerable(Of TSource)
- TSource
source
項目的類型。
- source
- IEnumerable<TSource>
一連串的值。
- element
- TSource
要新增在 source
開頭的值。
IEnumerable<TSource>
以 element
開頭的新序列。
source
為 null
。
下列程式代碼範例示範如何使用 Prepend 在序列開頭加上值。
C#
// Creating a list of numbers
List<int> numbers = new List<int> { 1, 2, 3, 4 };
// Trying to prepend any value of the same type
numbers.Prepend(0);
// It doesn't work because the original list has not been changed
Console.WriteLine(string.Join(", ", numbers));
// It works now because we are using a changed copy of the original list
Console.WriteLine(string.Join(", ", numbers.Prepend(0)));
// If you prefer, you can create a new list explicitly
List<int> newNumbers = numbers.Prepend(0).ToList();
// And then write to the console output
Console.WriteLine(string.Join(", ", newNumbers));
// This code produces the following output:
//
// 1, 2, 3, 4
// 0, 1, 2, 3, 4
// 0, 1, 2, 3, 4
' Creating a list of numbers
Dim numbers As New List(Of Integer)(New Integer() {1, 2, 3, 4})
' Trying to prepend any value of the same type
numbers.Prepend(0)
' It doesn't work because the original list has not been changed
Console.WriteLine(String.Join(", ", numbers))
' It works now because we are using a changed copy of the original list
Console.WriteLine(String.Join(", ", numbers.Prepend(0)))
' If you prefer, you can create a new list explicitly
Dim newNumbers As List(Of Integer) = numbers.Prepend(0).ToList
' And then write to the console output
Console.WriteLine(String.Join(", ", newNumbers))
' This code produces the following output:
'
' 1, 2, 3, 4
' 0, 1, 2, 3, 4
' 0, 1, 2, 3, 4
注意
這個方法不會修改集合的專案。 相反地,它會使用新元素建立集合的複本。
產品 | 版本 |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.6, 2.0, 2.1 |