Sunday, April 17, 2011

C# Easy question, how do I loop through an array and display values inline?

Hi all,

Basically I have this which I know won't work but I it illustrates what I'm trying to do:

MessageBox.Show("Found these: " + keywords[i] + " keywords.");

And I need to see this:

Found these: Item1, Item2 keywords.

There may be 1 keyword there may be 4, how should I do this?

Many thanks.

From stackoverflow
  • You could use string.Join:

    MessageBox.Show("Found these: " + string.Join(", ", keywords) 
                    + " keywords.");
    
  • Jon Skeet has a good answer with string.Join. your other option for more complicated formatting would be to use a string builder

    StringBuilder sb = new StringBuilder();
    seperator = "";
    foreach(string current in keywords){
     sb.Append(seperator);
     sb.Append(current);
     seperator = ", ";
    }
    
    MessageBox.Show("Found these: " + sb.ToString() + " keywords.");
    
    PoweRoy : sb.Length -= 2; // Remove the last ", " Should only happen when a string is in keywords else sb has a negative length and i dont know how it handles it :P

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.