Posted by: Cirilo Meggiolaro | 01/14/2009

Tip of the day #92 – Reverse Method – Enumerable class

One more useful method from the Enumerable class: Reverse method. The name says it all. The idea is to invert the order of the elements in a sequence.

Method signature

The following method signature is available:

public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source);

Example

For this example we are going to create a list of integers and display the integers starting on the last one and one by one until the first item in the collection.

List<int> myList = { 2, 4, 5, 7, 8, 9, 13, 15, 16, 17, 19, 21 };

foreach (int i in myList.Reverse<int>())
{
    Console.WriteLine(i);
}

Output

21
19
17
16
15
13
9
8
7
5
4
2

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: