Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use StringBuilder elements in a foreach?

Since I'm using .NET 1.1, I can't use a generic List of string, as generics were not part of the language yet. So I'm trying to use a StringBuilder, but get this err msg:

"foreach statement cannot operate on variables of type 'System.Text.StringBuilder' because 'System.Text.StringBuilder' does not contain a definition for 'GetEnumerator', or it is inaccessible"

with this code:

public StringBuilder linesToSend;
. . .

foreach (string _line in this.linesToSend)
{
    serialPort.Write(_line);
}

Is there something wrong with my code, or is StringBuilder really disallowed from foreach loops? If the latter, is String[] my best recourse?

like image 264
B. Clay Shannon-B. Crow Raven Avatar asked Feb 11 '13 18:02

B. Clay Shannon-B. Crow Raven


2 Answers

Old question, I know, but something potentially useful:

If each of your strings were built with .AppendLine or you inserted a new line, you can do

string[] delim = { Environment.NewLine, "\n" }; // "\n" added in case you manually appended a newline
string[] lines = StringBuilder.ToString().Split(delim, StringSplitOptions.None);
foreach(string line in lines){
    // Do something
}
like image 53
Jason McKindly Avatar answered Oct 09 '22 18:10

Jason McKindly


A StringBuilder doesn't store the lines that you append. It simply is used to build the final string. Assuming you've added everything to the StringBuilder already, you can do:

// Write the complete string to the serialPort
serialPort.Write(linesToSend.ToString());
like image 34
Justin Niessner Avatar answered Oct 09 '22 18:10

Justin Niessner