I have problem with List<T>.Reverse()
and Reverse(this IEnumerable<TSource> source)
.
Look to the code:
// Part 1
List<int> list = new List<int> { 1, 2, 3 };
foreach (int x in list)
Console.Write(x);
Console.WriteLine();
list.Reverse();
foreach (int x in list)
Console.Write(x);
Console.WriteLine();
list.Reverse();
// Part2
IList<int> ilist = list;
foreach (int x in list)
Console.Write(x);
Console.WriteLine();
ilist.Reverse();
foreach (int x in ilist)
Console.Write(x);
Console.WriteLine();
ilist.Reverse();
My result:
123
321
123
123
because Reverse()
-Part1 is List<T>.Reverse()
, Reverse()
-Part2 is Reverse(this IEnumerable<TSource> source)
I want execute List<int>.Reverse()
in Part2 for IList<int>
. How I can do it?
IList<int>
doesn't have aReverse
method, so it uses the extension method. The only way to useList<T>.Reverse
on yourIList<int>
reference is to cast or convert it to aList<int>
. Casting will only work if you're sure that it's really aList<int>
in the first place:Another option would be to create a
List<int>
from yourIList<int>
instance, rather than assuming it already is aList<int>
:The reason that the
Reverse
extension method doesn't actually affect the underlying list is because it operates onIEnumerable<T>
, which isn't necessarily writeable (none of theEnumerable
extension methods make changes to the original collection, they return a new collection).To use this version of
Reverse
, just use the product of theReverse
call, rather than the original list:In the second example, you're using an extension method against
IEnumerable<T>
, and this is not mutating the original collection but rather producing a query that would result in a sequence of your original list in reverse order. That is to say, if you want to utilize the results ofilist.Reverse()
, you would say