I would like to use an IEnumerable to generate a sequence of values — specifically, a list of Excel-like column headers.
private IEnumerable<string> EnumerateSymbolNames()
{
foreach (var sym in _symbols)
{
yield return sym;
}
foreach (var sym1 in _symbols)
{
foreach (var sym2 in _symbols)
{
yield return sym1 + sym2;
}
}
yield break;
}
private readonly string[] _symbols = new string[] { "A", "B", "C", ...};
This works fine if I fetch the values from a foreach loop. But what I want is to use the iterator block as a state machine and fetch the next available column header in response to a user action. And this — consuming the generated values — is where I’ve run into trouble.
So far I’ve tried
return EnumerateSymbolNames().Take(1).FirstOrDefault();
return EnumerateSymbolNames().Take(1).SingleOrDefault();
return EnumerateSymbolNames().FirstOrDefault();
var enumerator = EnumerateSymbolNames().GetEnumerator();
enumerator.MoveNext();
return enumerator.Current;
… but none of these have worked. (All repeatedly return “A”.)
Based on the responses to this question, I’m wondering what I want is even possible — although several of the responses to that post suggest techniques similar to my last one.
And no, this is not a homework assignment 🙂
When you use
GetEnumerator, you need to use the same enumerator for each iteration. If you call GetEnumerator a second time, it will start over at the beginning of the collection.If you want to use
Take, you must firstSkipthe number of records that have already been processed.