How to reverse a generic list without changing the same list?
Asked Answered
M

4

19

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
}
Mother answered 30/9, 2013 at 19:16 Comment(1)
Is the list being passed in, is it an instance field of that type, is it generated from a call to a method, or something else?Ralina
R
42

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.

Ralina answered 30/9, 2013 at 19:19 Comment(0)
B
7

You're asking how to create a reversed copy of the list, without mutating the original.

LINQ can do that:

foreach (var t1 in Enumerable.Reverse(t.List))
Bussard answered 30/9, 2013 at 19:19 Comment(0)
D
0

You can do one of two things. Either take out reversing the list from the method and reverse the list once before calling the method four times, or do:

List<My_Type> new_list = new List<Int32>(t.List);
new_list.Reverse();

That takes a copy of the list before reversing it so you don't touch the original list.

I would recomend the first approach because right now you are calling Reverse four times instead of just once.

Dr answered 30/9, 2013 at 19:21 Comment(0)
E
0

All the given options until now internally copy all elements to another list in reverse order, explicit as new_list.Reverse() or implicit t.List.AsEnumerable().Reverse(). I prefer something that has not this cost as the extension method below.

public class ListExtetions {
    public static IEnumerable<T> GetReverseEnumerator(this List<T> list) {
         for (int i = list.Count - 1; i >= 0; i--)
               return yeild list[i];
    }
}

And could be used as

foreach (var a in list.GetReverseEnumerator()) {

}
Edge answered 9/8, 2017 at 18:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.