简体   繁体   中英

string.Format with string.Join

I've tried making a string like this:

[1][2][3][4][5][6][7][8][9][10]

With this code:

string nums = "[" + string.Join("][", Enumerable.Range(1, 10)) + "]";

That, however, doesn't really look very good, so I was wondering if I could combine string.Format with string.Join , sort of like this:

string num = string.Join("[{0}]", Enumerable.Range(1, 10));

So that it wraps something around each item. However, that ends up like this:

1[{0}]2[{0}]3[{0}]4[{0}]5[{0}]6[{0}]7[{0}]8[{0}]9[{0}]10

Is there a better/easier way to do this?


Among all the solutions, I must say I prefer this

string s = string.Concat(Enumerable.Range(1, 4).Select(i => string.Format("SomeTitle: >>> {0} <<<\n", i)));

Over this

string s2 = "SomeTitle: >>>" + string.Join("<<<\nSomeTitle: >>>", Enumerable.Range(1, 4)) + "<<<\n";

Because all the formatting is done in one string, not in multiple.

string.Concat(Enumerable.Range(1,10).Select(i => string.Format("[{0}]", i)))

I wanted something like this, but with a possibility to enter a format string and a separator. So this is what I came up with:

public static string JoinFormat<T>(this IEnumerable<T> list, string separator,
                                   string formatString)
{
    formatString = string.IsNullOrWhiteSpace(formatString) ? "{0}": formatString;
    return string.Join(separator,
                       list.Select(item => string.Format(formatString, item)));
}

Now you could make a list like

[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

by entering numbers.JoinFormat(", ", "[{0}]") .

Whereas a Concat solution with "[{0}],") would have a trailing comma.

An empty or null separator produces your list.

You are probably looking for a LINQ solution such as

string nums = String.Concat(Enumerable.Range(1, 10)
                                      .Select(i => string.Format("[{0}]", i)))

I'd just concatenate each item, and use String.Concat to put them together:

string num =
  String.Concat(
    Enumerable.Range(1, 10).Select(n => "[" + n + "]")
  );

If you want to get fancy, you can make a cross join between the numbers and a string array. :)

string num =
  String.Concat(
    from n in Enumerable.Range(1, 10)
    from s in new string[] { "[", null, "]" }
    select s ?? n.ToString()
  );
StringBuilder str = new StringBuilder();
for (int i = 1; i <= 10; i++)
    str.AppendFormat("[{0}]", i);

Console.WriteLine(str.ToString());

My recommendation is to use StringBuilder to append the same pattern.

string.Join(',', Enumerable.Range(1, 10).Select(i => string.Format("'{0}'", i)))

String Join can be better option than Concat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM