I understand the considerable advantages of using a StringBuilder under many circumstances (rather than repeatedly concatenating a string over and over), but say I'm in a loop that requires me to, on every lap, evaluate the string's current contents?
I'm assuming a StringBuilder is not useful there, because it involves the repeated use of StringBuilder.ToString(); which flies in the face of a StringBuilder's advantages.
In my example below, what would you suggest is the most efficient way to go about replacing the StringBuilder?
Imagine that the following function's incoming 'listIncoming' parameter contains many strings, including the two strings indicated at the following 'listIncoming' indexes:
List Item 56: "I want to say Hello"
List Item 57: "World, I'm ready for you"
Now imagine that this list is sent to the following function; with the understanding that if "Hello" is ever found to immediately precede "World", then the loop should be exited...
private string BuildUpStringToReturn(List listIncoming) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < listIncoming.Count; i++) { sb.Append(listIncoming); if (sb.ToString().Contains("Hello World") { break; // It's time to get out! } } return sb.ToString(); } Short of inefficiently checking the current status of sb.ToString() in every loop iteration above, I'm wondering if there's an alternative you'd suggest. If the only alternative is to use a string inside the sample function, I'll accept that answer. It would just help to know.
Possible 'workaround' alternatives I'm contemplating (both of which would avoid the need for the above function)...
- Use other means to turn the list into a string (say, 'String.Join' for example)... and then look to see if that string contains "Hello World".
- While populating the list, make sure "Hello" and "World" will never appear consecutively.
- Any other ideas you'd suggest...
Источник: https://stackoverflow.com/questions/780 ... alternativ