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>
.
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"}
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With