-2

I have a List<int> that can contain between 1 and n values.

Lets say their are four integers {3,11,108,32} I need to construct the list of integers into a string like this

(3,11,108,32) - ie. Comma delimited

I realise this is very trivial, but I am looking for the most efficient solution.

For example, if you only have one item, there shouldn't be a comma in the string, but there should be between all additional items.

Sayse
  • 38,955
  • 14
  • 69
  • 129
Steve
  • 2,054
  • 3
  • 20
  • 31

3 Answers3

6

Use String.Join and String.Format to avoid creation of many in-memory sub-strings:

String.Format("({0})", String.Join(",", listOfIntegers))

Here two strings will be created. You can also use StringBuilder and build string manually:

StringBuilder builder = new StringBuilder();
builder.Append("(");
foreach (var value in listOfIntegers)
    builder.AppendFormat("{0},", value);
if (builder.Length > 1)
    builder.Remove(builder.Length - 1, 1);
builder.Append(")");
var result = builder.ToString();

But I would go with first approach, especially if list of integers is not very big.

Sergey Berezovskiy
  • 215,927
  • 33
  • 392
  • 421
  • 1
    +1 But i would really prefer `String.Join` since it's much more readable. It's also more efficient unless you don't want to concat millions of items. If i remember correctly it uses also a `StringBuilder` internally if required. Side-note: instead of `builder.Remove(builder.Length - 1, 1)` you can use `builder.Length--` – Tim Schmelter Jun 24 '14 at 06:53
1

If you use .NET 4+, you can use String.Join(String, IEnumerable<T>) overload.

Here an example on LINQPad;

List<int> ints  = new List<int>(){3, 11, 108, 32};
string joined = string.Join(",", ints);
string.Format("({0})", joined).Dump();

Output will be;

(3,11,108,32)
Soner Gönül
  • 91,172
  • 101
  • 184
  • 324
0

Since I'm a big fan of Extension methods, I'll use one here.

First the extension method:

public static class Extensions
{
    public static void ForEachElement<T>(this IEnumerable<T> @enum, Action<T> mapFunction)
    {
        foreach (var item in @enum) mapFunction(item);
    }
}

This extension method allows me to, for each element in an Ienumerable, execute a specified action.

Then to format your list of int's to a string, you can do:

 var numbers = new List<int>() { 10, 11, 4, 5, 9, 12 };

 var sb = new StringBuilder();
 sb.Append("(");
 numbers.ForEachElement(x => sb.Append(x.ToString(CultureInfo.InvariantCulture) + ","));

 string output = sb.ToString().TrimEnd(new[] { ',' }) + ")";
 MessageBox.Show(output);

This will produce the output:

(10,11,4,5,6,12)

Complexity
  • 5,148
  • 3
  • 28
  • 76