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<>()?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With