Before jumping to LINQ... which doesn't solve any problems you've described, let's look at the logic you have here.
- We split a string with a 'pattern'. How?
- We then create a new list of codes. How?
- We then loop through those codes and decode them. How?
- But since we forgot to keep track of where those code came from, we now loop through the equationList (which is an array, not a
List<T>
) to substitute the results.
Seems a little convoluted to me.
Maybe a simpler solution would be:
- Take in a
string
, and return IEnumerable<string>
of words (similar to what you do now).
- Take in a
IEnumerable<string>
of words, and return a IEnumerable<?>
of values.
That is to say with this second step iterate over the strings, and simply return the value you want to return - rather than trying to extract certain values out, parsing them, and then inserting them back into a collection.
//Ideally we return something more specific eg, IEnumerable<Tokens>
public IEnumerable<string> ParseEquation(IEnumerable<string> words)
{
foreach (var word in words)
{
if (IsOperator(word)) yield return ToOperator(word);
else if (IsCode(word)) yield return ToCode(word);
else ...;
}
}
This is quite similar to the LINQ Select Statement... if one insisted I would suggest writing something like so:
var tokens = equationList.Select(ToToken);
...
public Token ToToken(string word)
{
if (IsOperator(word)) return ToOperator(word);
else if (IsCode(word)) return ToCode(word);
else ...;
}
If GetCodeValue(code) doesn't already, I suggest it probably could use some sort of caching/dictionary in its implementation - though the specifics dictate this.
The benefits of this approach is that it is flexible (we can easily add more processing steps), simple to follow (we put in these values and get these as a result, no mutating state) and easy to write. It also breaks the problem down into nice little chunks that solve their own task, which will help immensely when trying to refactor, or find niggly bugs/performance issues.