Enumerable.Reverse<TSource>(IEnumerable<TSource>) 方法

定义

反转序列中元素的顺序。

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

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

要反转的值序列。

返回

IEnumerable<TSource>

一个序列,其元素以相反顺序对应于输入序列的元素。

例外

sourcenull

示例

下面的代码示例演示如何使用 Reverse 来反转数组中元素的顺序。

C#
char[] apple = { 'a', 'p', 'p', 'l', 'e' };

char[] reversed = apple.Reverse().ToArray();

foreach (char chr in reversed)
{
    Console.Write(chr + " ");
}
Console.WriteLine();

/*
 This code produces the following output:

 e l p p a
*/

注解

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

与 不同 OrderBy,此排序方法在确定顺序时不考虑实际值本身。 相反,它只是以基础源生成元素的相反顺序返回元素。

适用于

产品 版本
.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 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0