[ACCEPTED]-How does IEnumerable<T>.Reverse work?-collections

Accepted answer
Score: 49

In short, it buffers everything and then 10 walks through it backwards. Not efficient, but 9 then, neither is OrderBy from that perspective.

In 8 LINQ-to-Objects, there are buffering operations 7 (Reverse, OrderBy, GroupBy, etc) and non-buffering 6 operations (Where, Take, Skip, etc).

As an 5 example of a non-buffering Reverse implementation 4 using IList<T>, consider:

public static IEnumerable<T> Reverse<T>(this IList<T> list) {
    for (int i = list.Count - 1; i >= 0; i--) {
        yield return list[i];

Note that this is still 3 a little susceptible to bugs if you mutate 2 the list while iterating it... so don't 1 do that ;-p

Score: 6

It works by copying the underlying IEnumerable<T> to 7 an array, then enumerating over that array 6 backward. If the underlying IEnumerable<T> implements ICollection<T> (like T[], List<T>, etc.), then the copy step is skipped and the enumerator just iterates over the underlying collection directly.

For more information, check out 5 System.Linq.Buffer<TElement> in Reflector.

Edit: The 4 underlying collection is always copied, even 3 if it's an ICollection<TElement>. This 2 prevents changes in the underlying collection 1 from being propagated by the Buffer<TElement>.

Score: 3

it loads all items to memory and then steps 2 through them (backwards). this is far less 1 efficient.

More Related questions