Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a generic list without changing the same list?

I have a generic list that is being used inside a method that's being called 4 times. This method writes a table in a PDF with the values of this generic list.

My problem is that I need to reverse this generic list inside the method, but I'm calling the method 4 times so the list is being reversed every time I call the method and I don't want that... what can I do? Is there a way to reverse the list without mutating the original?

This is inside the method:

t.List.Reverse();
foreach (string t1 in t.List)
{
    //Some code
}
like image 818
Phoenix_uy Avatar asked Sep 30 '13 19:09

Phoenix_uy


People also ask

How do you reverse a list in Python without affecting the original list?

Using the reversed() method and reverse() method, we can reverse the contents of the list object in place i.e., we don't need to create a new list instead we just copy the existing elements to the original list in reverse order. This method directly modifies the original list.

How do I reverse a list and store in another list in Python?

In Python, there is a built-in function called reverse() that is used to revers the list. This is a simple and quick way to reverse a list that requires little memory. Syntax- list_name. reverse() Here, list_name means you have to write the name of the list which have to be reversed.

How do I reverse the order of a list in C#?

Reverse() method. To reverse the order of the elements within the specified list, we can use the List<T>. Reverse() method. List<T>.


1 Answers

The "easy" option would be to just iterate the list in reverse order without actually changing the list itself instead of trying to reverse it the first time and know to do nothing the other times:

foreach (string t1 in t.List.AsEnumerable().Reverse())
{
    //Some code
}

By using the LINQ Reverse method instead of the List Reverse, we can iterate it backwards without mutating the list. The AsEnumerable needs to be there to prevent the List Reverse method from being used.

like image 87
Servy Avatar answered Sep 22 '22 13:09

Servy