Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse<> and Reverse

Tags:

c#

reverse

I have a question about reversing the elements of a list in C#.

The ultimate goal is to get the last N elements of a list.

Suppose I have a list of decimals.

List<decimal> listOfDecimals = new List<decimal>() { 1.5m, 2.4m, 3.6m, 0.1m };

This is my attempt to get a list containing the last 2 elements of listOfDecimals.

List<decimal> listOfLastTwoElements = listOfDecimals.Reverse<decimal>().Take<decimal>(2).Reverse<decimal>().ToList<decimal>();

My question is, if I replaced Reverse<>() with Reverse(), there is a syntax error as flagged by VS.

Can anyone please let me know when I should use Reverse(), and when to use Reverse<>()?

like image 440
Roy Avatar asked Jan 10 '23 09:01

Roy


1 Answers

This is because List itself has a Reverse method. This reverse method does not return anything.

The reverse method on List<T> takes precedence over the extension method on IEnumerable<T>. Confusing is that when you just have an IEnumerable<T>, you can use Reverse() without type argument. Then the type inference of the compiler resolves the generic type argument. So the extension method looks the same as the method on List<T>.

var reversed1 = Enumerable.Empty<int>().Reverse(); // works
var reversed2 = Enumerable.Empty<int>().Reverse<int>(); // works and is the same as the line above.

var reversed3 = new List<int>().Reverse(); // does not work
var reversed4 = new List<int>().Reverse<int>(); // works
like image 83
Ruben Avatar answered Jan 20 '23 09:01

Ruben