Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating an array of strings to "string1, string2 or string3"

Tags:

string

c#

.net

Consider the following code:

string[] s = new[] { "Rob", "Jane", "Freddy" };

string joined = string.Join(", ", s);

// joined equals "Rob, Jane, Freddy"

For UI reasons I might well want to display the string "Rob, Jane or Freddy".

Any suggestions about the most concise way to do this?

Edit

I am looking for something that is concise to type. Since I am only concatenating small numbers (<10) of strings I am not worried about run-time performance here.

like image 338
Richard Ev Avatar asked Apr 06 '09 14:04

Richard Ev


1 Answers

Concise meaning to type? or to run? The fastest to run will be hand-cranked with StringBuilder. But to type, probably (edit handle 0/1 etc):

string joined;
switch (s.Length) {
    case 0: joined = ""; break;
    case 1: joined = s[0]; break;
    default:
        joined = string.Join(", ", s, 0, s.Length - 1)
               + " or " + s[s.Length - 1];
        break;
} 

The StringBuilder approach might look something like:

static string JoinOr(string[] values) {
    switch (values.Length) {
        case 0: return "";
        case 1: return values[0];
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < values.Length - 2; i++) {
        sb.Append(values[i]).Append(", ");
    }
    return sb.Append(values[values.Length-2]).Append(" or ")
        .Append(values[values.Length-1]).ToString();
}
like image 81
Marc Gravell Avatar answered Nov 15 '22 23:11

Marc Gravell