[c#] Simple IEnumerator use (with example)

I am having trouble remembering how (but not why) to use IEnumerators 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.

This question is related to c# ienumerator

The answer is


I'd do something like:

private IEnumerable<string> DoWork(IEnumerable<string> data)
{
    List<string> newData = new List<string>();
    foreach(string item in data)
    {
        newData.Add(item + "roxxors");
    }
    return newData;
}

Simple stuff :)


Also you can use LINQ's Select Method:

var source = new[] { "Line 1", "Line 2" };

var result = source.Select(s => s + " roxxors");

Read more here Enumerable.Select Method


If i understand you correctly then in c# the yield return compiler magic is all you need i think.

e.g.

IEnumerable<string> myMethod(IEnumerable<string> sequence)
{
    foreach(string item in sequence)
    {
         yield return item + "roxxors";
    }
}

public IEnumerable<string> Appender(IEnumerable<string> strings)
{
  List<string> myList = new List<string>();
  foreach(string str in strings)
  {
      myList.Add(str + "roxxors");
  }
  return myList;
}

or

public IEnumerable<string> Appender(IEnumerable<string> strings)
{
  foreach(string str in strings)
  {
      yield return str + "roxxors";
  }
}

using the yield construct, or simply

var newCollection = strings.Select(str => str + "roxxors"); //(*)

or

var newCollection = from str in strings select str + "roxxors"; //(**)

where the two latter use LINQ and (**) is just syntactic sugar for (*).