Is there a way to use yield blocks to implement an IEnumerator<T>
which can go backward (MoveLast()
) as well as forward?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
I know this thread is super old but it is relevant to note that
... is get compiled into:
So if you don't mind the "MoveNext" syntax, you could easily implement IEnumerator and add a "MovePrevious". You wouldn't be able to reverse direction if you use "foreach" but you'd be able to reverse direction if using a while loop.
Or... if you want to "foreach" a list in reverse direction (not bidirectional) you could take advantage of the yield statement.
Or... if you want to foreach in reverse by going the long route you can implement your own IEnumerable/IEnumerator
Actually, there seems to be an approach described in Accelerated C# 2008. Unfortunately, two pages are not visible in the preview, and it has to rely on reflection (the results of which can be cached, as usual) but you can get the gist.
Not directly from the iterator block, no.
However, the caller can always buffer the results, for example into a
List<T>
, or just callReverse()
- but this doesn't always apply.C5 Collections library (http://www.itu.dk/research/c5/) implements collections and linked list with backwards enumeration. The project is OpenSource so you should be able to find answer there.
No. One of the limitations of IEnumerator is that it holds its current state, and it doesn't remember its prior state. As a result, IEnumerable is forward-only.
If you need to hold onto prior states, read the IEnumerable into a List or LinkedList and enumerate through those objects instead.
No. Using
yield
results in anIEnumerable
which is unidirectional.