I am having trouble remembering how (but not why) to use IEnumerator
s in C#. I am used to Java with its wonderful documentation that explains everything to beginners quite nicely. So please, bear with me.
I have tried learning from other answers on these boards to no avail. Rather than ask a generic question that has already been asked before, I have a specific example that would clarify things for me.
Suppose I have a method that needs to be passed an IEnumerable<String>
object. All the method needs to do is concatenate the letters roxxors
to the end of every String
in the iterator. It then will return this new iterator (of course the original IEnumerable
object is left as it was).
How would I go about this? The answer here should help many with basic questions about these objects in addition to me, of course.
Here is the documentation on
IEnumerator
. They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes fromenumerate
, which means "to count off or name one by one".IEnumerator
andIEnumerator<T>
is provided by allIEnumerable
andIEnumerable<T>
interfaces (the latter providing both) in .NET viaGetEnumerator()
. This is important because theforeach
statement is designed to work directly with enumerators through those interface methods.So for example:
Becomes:
As to your specific scenario, almost all collections in .NET implement
IEnumerable
. Because of that, you can do the following:If i understand you correctly then in c# the
yield return
compiler magic is all you need i think.e.g.
or
using the yield construct, or simply
or
where the two latter use LINQ and
(**)
is just syntactic sugar for(*)
.Also you can use LINQ's Select Method:
Read more here Enumerable.Select Method
I'd do something like:
Simple stuff :)