string.Join on a List<int> or other type

C#ArraysString

C# Problem Overview


I want to turn an array or list of ints into a comma delimited string, like this:

string myFunction(List<int> a) {
    return string.Join(",", a);
}

But string.Join only takes List<string> as the second parameter. What is the best way to do this?

C# Solutions


Solution 1 - C#

The best way is to upgrade to .NET 4.0 where there is an overload that does what you want:

If you can't upgrade, you can achieve the same effect using Select and ToArray.

    return string.Join(",", a.Select(x => x.ToString()).ToArray());

Solution 2 - C#

A scalable and safe implementation of a generic enumerable string join for .NET 3.5. The usage of iterators is so that the join string value is not stuck on the end of the string. It works correctly with 0, 1 and more elements:

public static class StringExtensions
{
    public static string Join<T>(this string joinWith, IEnumerable<T> list)
    {
        if (list == null)
            throw new ArgumentNullException("list");
        if (joinWith == null)
            throw new ArgumentNullException("joinWith");

        var stringBuilder = new StringBuilder();
        var enumerator = list.GetEnumerator();

        if (!enumerator.MoveNext())
            return string.Empty;

        while (true)
        {
            stringBuilder.Append(enumerator.Current);
            if (!enumerator.MoveNext())
                break;

            stringBuilder.Append(joinWith);
        }

        return stringBuilder.ToString();
    }
}

Usage:

var arrayOfInts = new[] { 1, 2, 3, 4 };
Console.WriteLine(",".Join(arrayOfInts));

var listOfInts = new List<int> { 1, 2, 3, 4 };
Console.WriteLine(",".Join(listOfInts));

Enjoy!

Solution 3 - C#

.NET 2.0:

static string IntListToDelimitedString(List<int> intList, char Delimiter)
{
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < intList.Count; i++)
    {
        builder.Append(intList[i].ToString());

        if (i != intList.Count - 1)
            builder.Append(Delimiter);
    }

    return builder.ToString();
}

Solution 4 - C#

In .NET the list class has a .ToArray() method. Something like this could work:

string myFunction(List<int> a)
{
    return string.Join(",", a.ToArray());
}

Ref: List<T> Methods (MSDN)

Solution 5 - C#

Had a similar Extension Method that I modified to this

public static class MyExtensions
{
    public static string Join(this List<int> a, string splitChar)
    {
        return string.Join(splitChar, a.Select(n => n.ToString()).ToArray());
    }
}

and you use it like this

var test = new List<int>() { 1, 2, 3, 4, 5 };
string s = test.Join(",");

.NET 3.5

Solution 6 - C#

This answer is for you if you don't want to venture into the depths of .NET 4.0 just yet.

String.Join() concatenates all the elements of a string array, using the specified separator between each element.

The syntax is

public static string Join(
    string separator,
    params string[] value
)

Rather than passing your List of ints to the Join method, I suggest building up an array of strings first.

Here is what I propose:

static string myFunction(List<int> a) {
    int[] intArray = a.ToArray();
    string[] stringArray = new string[intArray.Length];

    for (int i = 0; i < intArray.Length; i++)
    {
        stringArray[i] = intArray[i].ToString();
    }

    return string.Join(",", stringArray);
}

Solution 7 - C#

Using .NET 4.0

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string s = myFunction(PopulateTestList());
        this.TextBox1.Text = s;
    }

    protected List<int> PopulateTestList()
    {
        List<int> thisList = new List<int>();
        thisList.Add(22);
        thisList.Add(33);
        thisList.Add(44);

        return thisList;
    }

    protected string myFunction(List<int> a)
    {
        return string.Join(",", a);
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCode CommanderView Question on Stackoverflow
Solution 1 - C#Mark ByersView Answer on Stackoverflow
Solution 2 - C#DeletedView Answer on Stackoverflow
Solution 3 - C#Kyle RosendoView Answer on Stackoverflow
Solution 4 - C#wintochView Answer on Stackoverflow
Solution 5 - C#Jonas ElfströmView Answer on Stackoverflow
Solution 6 - C#GregView Answer on Stackoverflow
Solution 7 - C#user436001View Answer on Stackoverflow