I am having a difficult time with a seemingly easy and embarrassing problem. All I want is the next element in an IEnumberable without using Skip(1).Take(1).Single(). This example illustrates the basic problem.
private char _nextChar;
private IEnumerable<char> getAlphabet()
{
yield return 'A';
yield return 'B';
yield return 'C';
}
public void sortAlphabet()
{
foreach (char alpha in getAlphabet())
{
switch (alpha)
{
case 'A': //When A pops up, I want to get the next element, ie 'B'
_nextChar = getAlphabet().Skip(1).Take(1).Single();
break;
case 'B': //When B pops up, I want 'C' etc
_nextChar = getAlphabet().Skip(1).Take(1).Single();
break;
}
}
}
Other than being ugly, this example works. But let’s say that the IEnumerable contained 2 million elements, then the LINQ statement makes the program execute unbearably slow. What I want is simple. I just want the next element in an IEnumberable<>. All my problems would be solved if there was a function like:
_nextChar = getAlphabet().moveNext() //or getNext()
It is much preferred if the solution keeps the same structure/layout/functionality of the example however, I am flexible. My program is a file parser, and among the 2 million lines of text are some keys like “money=324” where “money” and “324” are neighbor elements in the IEnumberable and when the parser comes across “money” I want “324”. (who doesn’t? 😀 Sorry for bad pun.)
There is a function exactly like that. It just belongs to
IEnumerator<T>, notIEnumerable<T>!Here’s a question for you, though. Is it necessary that this code use an
IEnumerable<char>, rather than anIList<char>? I ask because, as if this weren’t obvious, the code would be much simpler if you had random access to the items returned bygetAlphabetby index (and if someone is tempted to point out that you can do this withElementAt, please, just get that idea out of your head right now).I mean, consider what the code would look like in this case:
Isn’t that much easier?