Sometimes you don't have the luxury of indexing, or perhaps you want to reverse the results of a Linq query, or maybe you don't want to modify the source collection, if any of these are true, Linq can help you.
A Linq extension method using anonymous types with Linq Select to provide a sorting key for Linq OrderByDescending;
public static IEnumerable<T> Invert<T>(this IEnumerable<T> source)
{
var transform = source.Select(
(o, i) => new
{
Index = i,
Object = o
});
return transform.OrderByDescending(o => o.Index)
.Select(o => o.Object);
}
Usage:
var eable = new[]{ "a", "b", "c" };
foreach(var o in eable.Invert())
{
Console.WriteLine(o);
}
// "c", "b", "a"
It is named "Invert" because it is synonymous with "Reverse" and enables disambiguation with the List Reverse implementation.
It is possible to reverse certain ranges of a collection too, since Int32.MinValue and Int32.MaxValue are out of the range of any kind of collection index, we can leverage them for the ordering process; if an element index is below the given range, it is assigned Int32.MaxValue so that its order doesn't change when using OrderByDescending, similarly, elements at an index greater than the given range, will be assigned Int32.MinValue, so that they appear to the end of the ordering process. All elements within the given range are assigned their normal index and are reversed accordingly.
public static IEnumerable<T> Invert<T>(this IEnumerable<T> source, int index, int count)
{
var transform = source.Select(
(o, i) => new
{
Index = i < index ? Int32.MaxValue : i >= index + count ? Int32.MinValue : i,
Object = o
});
return transform.OrderByDescending(o => o.Index)
.Select(o => o.Object);
}
Usage:
var eable = new[]{ "a", "b", "c", "d" };
foreach(var o in eable.Invert(1, 2))
{
Console.WriteLine(o);
}
// "a", "c", "b", "d"
I'm not sure of the performance hits of these Linq implementations versus using a temporary List to wrap a collection for reversing.
At time of writing, I was not aware of Linq's own Reverse implementation, still, it was fun working this out. https://msdn.microsoft.com/en-us/library/vstudio/bb358497(v=vs.100).aspx