Difference between IEnumerable <T> .Reverse & List <T> .Reverse
Conceptually, this could be because IEnumerable used when you want to represent an immutable collection of elements. That is, you only want to read the items in the list, but not add / insert / delete or otherwise modify the collection. In this data view, the new IEnumerable is returned in a different order β the expected result. When you use List , you expected to be able to add / insert / delete or otherwise mutate the collection, so in this context, the Reverse method will be expected, which changes the order of the original list.
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 the second list, the reverse. Pay attention to,
List<String> names = new List<String>(); names.Reverse(); Cancels the original list. Hope this makes sense.
Because these are two different methods.
List<T>.Reverse is an instance method on List<T> . This changes the list in place.
Enumerable.Reverse<T> is an extension method on IEnumerable<T> . This creates a new sequence that lists the original sequence in reverse order.
You can use the latter in List<T> , calling as a static method:
var list = new List<string>{"1","2"}; var reversed = Enumerable.Reverse(list) Or by clicking on IEnumerable<T> :
IEnumerable<string> list = new List<string>{"1","2"}; var reversed = list.Reverse(); In both cases, list remains unchanged and reversed when the enumerated returns {"2","1"} .
These are different methods, remember. Essentially different, with nothing in common but a name.
void List.Reverse is a method of only the List instance, and it does the replacement of the list or part of it.
IEnumerable Enumerable.Reverse - This extension method (btw IList also has it!) Creates a new enumeration with the canceled order.
There is no such thing as IEnumerable<T>.Reverse() It Enumerable.Reverse<T>(this IEnumerable<T>) , and this extension method from Linq applies to all IEnumerable<> .
Now that we have established when they occur, it is easy to understand why they are so different. Linq adds methods to create βworkflows,β and this is achieved by creating a new instance each time.
List<T>.Reverse() is a List method and, like all its methods (for example, Add ), directly modifies the instance.
IEnumerable<T> has a basic implementation, which can be List<T> , Hashtable<T> or something else that implements IEnumerable.
List<T> is an implementation, so you can directly modify this instance.
Like everyone else, one of them is an extension method and part of Linq, and one of them is implemented directly on the type.