Reverse doesn't produce a new reversed list. The current list is updated. So in short your code should just be :
train.Reverse();
As a side note is this is your full code ? You are just testing ? It seems you'll run into another error (trying to access a non existing element plus reversing the list seems to serve no purpose at all).
train=train.Reverse(); // It is giving the compilation error.
Reverse() function has void as a return type & your are trying to assign void value to variable train which is accepting list of integers. See below its definition.
// public void
Reverse();
It reverses the order of the elements in the entire System.Collections.Generic.List<T> so no need to assign it back to list.
See the demo code:
List<int> train = new List<int>();
train.Add(1);
train.Add(2);
train.Insert(0, 3); // or train[0] = 5; // You can add wagonId either by giving array index to list or by using List<T> Insert() function where the first argument is index // of list & second argument is the item needs to be insert.
train.Reverse();
foreach (var item in train)
{
Console.WriteLine(item);
}
Console.ReadLine();
Member
2 Points
32 Posts
list<T> reverse issue
Nov 09, 2017 04:44 AM|merrittr|LINK
I have code like this
but the 2 lines where I am assignmg train to itself reversed I get
any idea what is wrong ... I am trying to add a list item to the left side is the point of the reversing
All-Star
48730 Points
18189 Posts
Re: list<T> reverse issue
Nov 09, 2017 05:26 PM|PatriceSc|LINK
Hi,
See https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx
Reverse doesn't produce a new reversed list. The current list is updated. So in short your code should just be :
train.Reverse();
As a side note is this is your full code ? You are just testing ? It seems you'll run into another error (trying to access a non existing element plus reversing the list seems to serve no purpose at all).
Edit: ah missed what you needed. So you want to use (from https://msdn.microsoft.com/en-us/library/sey5k5z4(v=vs.110).aspx ) :
train.InsertAt(wagonId,0); // will always insert at the beginning of the list without having to reverse/unreverse.
IMO when you start to work with a class which is not familiar always have a look at the doc to get an idea about its capabilities.
None
0 Points
3 Posts
Re: list<T> reverse issue
Nov 12, 2017 06:02 PM|pankaj@dotnetlooker|LINK
Hi,
As per your code :
train=train.Reverse(); // It is giving the compilation error.
Reverse() function has void as a return type & your are trying to assign void value to variable train which is accepting list of integers. See below its definition.
// public void Reverse();
It reverses the order of the elements in the entire System.Collections.Generic.List<T> so no need to assign it back to list.
See the demo code:
Follow me@DotNet Looker