Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c# - Why there is two completely different version of Reverse for List and IEnumerable?

For the List object, we have a method called Reverse().
It reverse the order of the list 'in place', it doesn't return anything.

For the IEnumerable object, we have an extension method called Reverse().
It returns another IEnumerable.

I need to iterate in reverse order throught a list, so I can't directly use the second method, because I get a List, and I don't want to reverse it, just iterate backwards.

So I can either do this :

for(int i = list.Count - 1; i >=0; i--)

Or

foreach(var item in list.AsEnumerable().Reverse())

I found it less readable than if I have an IEnumerable, just do

foreach(var item in list.Reverse())

I can't understand why this 2 methods have been implemented this way, with the same name. It is pretty annoying and confusing.

Why there is not an extension called BackwardsIterator() in the place of Reverse() working for all IEnumerable?

I'm very interested by the historical reason of this choice, more than the 'how to do it' stuff!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is worth noting that the list method is a lot older than the extension method. The naming was likely kept the same as Reverse seems more succinct than BackwardsIterator.

If you want to bypass the list version and go to the extension method, you need to treat the list like an IEnumerable<T>:

var numbers = new List<int>();
numbers.Reverse(); // hits list
(numbers as IEnumerable<int>).Reverse(); // hits extension

Or call the extension method as a static method:

Enumerable.Reverse(numbers);

Note that the Enumerable version will need to iterate the underlying enumerable entirely in order to start iterating it in reverse. If you plan on doing this multiple times over the same enumerable, consider permanently reversing the order and iterating it normally.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...