Reverse Operator Part 11

Reverse is one of ordering query operator. Reverse operator simply returns the input sequence in the reverse order. It does not effect the elements in the input sequence in any way. The prototype of the reverse operator looks like this

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

From the prototype shown above, you will notice that it is an extension method that is available on any object that implements IEnumerable<T>.

Let's look at few examples of reverse operators.

image

CWindowssystem32cmd.exe

 

In the above example I am demonstrating the use of Reverse operator with two different type of collections, the first one is an array of names (string) and the second one is an array of numbers(integers). For both collections, I simply call Reverse on the collection to reverse the elements in the output sequence as shown in the output screen.

Reverse operator has no translation available in linq to SQL. Therefore if you try to use Reverse operator, you would get an runtime exception.

You can also use Reverse operator with linq to XML. Let's look at the example to understand the usage.

image

CWindowssystem32cmd.exe (2)

In the above example, I am using Reverse operator with linq to XML. First I make use of descendants operator to retrieve all the name nodes in the entire XML document. Then I reverse those nodes and apply the projection operator to select the name of each person as shown in the output screen. As you can see from the output on the screen and the original XML document, the names are printed in the reverse order.

2 Comments

Comments have been disabled for this content.