Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between IEnumerable<T>.Reverse & List<T>.Reverse [duplicate]

Why IEnumerable<T>.Reverse() returns the reversed collection with the original collection and List<T> reverses the original collection itself? This is somewhat confusing to me since List<T> inherits from IEnumerable<T>.

like image 547
Prasanna Avatar asked May 15 '15 15:05

Prasanna


3 Answers

Because they're two different methods.

List<T>.Reverse is an instance method on List<T>. This modifies the List in place.

Enumerable.Reverse<T> is an extension method on IEnumerable<T>. This creates a new sequence that enumerates the source sequence in reverse order.

You can use the latter on a List<T> by calling as a static method:

var list = new List<string>{"1","2"};
var reversed = Enumerable.Reverse(list)

Or by casting to IEnumerable<T>:

IEnumerable<string> list = new List<string>{"1","2"};
var reversed = list.Reverse();

In both these cases, list remains unchanged and reversed when enumerated returns {"2","1"}.

like image 92
Charles Mager Avatar answered Nov 06 '22 21:11

Charles Mager


Conceptually, this may be because IEnumerable is used when you want to represent an immutable collection of items. That is, you only want to read the items in the list, but not add/insert/delete or otherwise change the collection. In this view of the data, returning a new IEnumerable in a different order is the expected result. When you use a List, you expected to be able to add/insert/delete or otherwise mutate the collection, so a Reverse method that changes the order of the original list would be expected in that context.

As others have noted IEnumerable is an interface and List is a class. List implements IEnumerable.

So,

 IEnumerable<String> names = new List<String>();
 var reversedNames = names.Reverse();

gets you a second list, reversed. Whereas,

 List<String> names = new List<String>();
 names.Reverse(); 

Reverses your original list. I hope this makes sense.

like image 21
Kratz Avatar answered Nov 06 '22 20:11

Kratz


Reverse on IEnumerable<T> is part of Linq and is added as extension method (Enumerable.Reverse<T>). It was added after Reverse was implemented for List<T>.

IEnumerable<T> isn't a collection of objects either. It just tells the consumer how to get at those items.

like image 30
Daniel A. White Avatar answered Nov 06 '22 19:11

Daniel A. White