Enumerable.Prepend<TSource>(IEnumerable<TSource>, TSource) 方法

定义

向序列的开头添加值。

C#
public static System.Collections.Generic.IEnumerable<TSource> Prepend<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, TSource element);

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

值序列。

element
TSource

要放置在 source 前面的值。

返回

IEnumerable<TSource>

element 开头的新序列。

例外

sourcenull

示例

下面的代码示例演示如何使用 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

注解

备注

此方法不会修改集合的元素。 而是使用新元素创建集合的副本。

适用于

产品 版本
.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