Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Reverse -does it leave the variable changed or make a copy

Tags:

c#

linq

reverse

I have a dicionary of strings and dates

private readonly Dictionary<string, DateTime>

as a private member variable in a class

I have methods which recursively get the next and previous value in the dictionary given a particular key

e.g. It takes the given key, does a database lookup, if that is null, it gets the next one and so on recursively. It does this both forward and backwards

I have used this to get the next one Find next record in a set: LINQ

My question is can I simply add Reverse to the linq statement to do this backwards?

Obviously it will work but I am worried about the state it will leave my member variable list in

i.e. will it be reversed? or is a copy have made when doing the reverse?

thanks

like image 254
ChrisCa Avatar asked Dec 03 '25 09:12

ChrisCa


2 Answers

Enumerable.Reverse does not mutate the sequence on which it is invoked.

like image 82
jason Avatar answered Dec 05 '25 21:12

jason


As others have said, Enumerable.Reverse will not change the underlying sequence (except in the rare case where enumerating over the sequence will change it).

However, be warned that if you are using a List, you might end up calling List.Reverse, which DOES change the list.

List<int> list = /* initialize */;
IEnumerable<int> asEnumerable = list;

// these call List<int>.Reverse(), which changes the list
list.Reverse();
((List<int>)asEnumerable).Reverse();

// these call Enumerable.Reverse<int>(), which does not change the list, but returns a new IEnumerable<int>
asEnumerable.Reverse();
((IEnumerable<int>)list).Reverse();
((IList<int>)list).Reverse();

Sorry, I would have made this a comment on one of the other correct answers, but I wanted to include code.

like image 24
hypehuman Avatar answered Dec 05 '25 23:12

hypehuman