Reverse <> and reverse

I have a question about changing list items in C #.

The ultimate goal is to get the last N list items.

Suppose I have a list of decimal places.

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 will be a syntax error noted by VS.

Can someone please tell me when should I use Reverse () and when to use Reverse <> ()?

+4
source share
2 answers

This is due to the fact that the list has the Inverse method . This inverse method returns nothing.

List<T> IEnumerable<T>. , IEnumerable<T>, Reverse() . . , , 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
+9

Reverse() - List<T>, Reverse<T>() () IEnumerable<T>, List<T>.

2 IEnumerable, Last(2). IEnumerable<T>, , , , ToList.

List<T> also has a method `RemoveRange()`, so if you want to remove all but the last 2 elements:

listOfDecimals.RemoveRange(0, listOfDecimals.Count - 2)
0

Source: https://habr.com/ru/post/1544725/


All Articles