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

7

112

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?

Preciosity answered 31/8, 2010 at 15:16 Comment(2)
What version of C# / .NET are you using?Selfcontradiction
Possible duplicate of #3211922Taal
S
183

The best way is to upgrade to .NET 4.0 or later 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());
Selfcontradiction answered 31/8, 2010 at 15:17 Comment(7)
Also assumes he is at least on C# 3, .NET 3.5Heterotopia
Why use LINQ instead of the built-in ToArray method of List<T>?Leopoldeen
because he would have a List<int>. The linq select converts the List<int> to IEnumerable<string> and then to the array.Grapple
Upgrading to 4.0 is not practical in my situation, but the LINQ solution is exactly what I was looking for. Thanks!Preciosity
@gbogumil: Sorry, didn't notice it was an int.Leopoldeen
This is also usable for other methods then ToString(), e.g. a.Select(x => x.Code).ToArray());Sinistrality
.ToArray() can be avoid since Join method accepts IEnumerable<string>Statistics
M
9

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)

Manfred answered 31/3, 2014 at 23:8 Comment(1)
This answer from 2010 already states that, as ToString is implied when doing a string.Join.Willettawillette
P
5

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!

Prowess answered 31/8, 2010 at 15:52 Comment(2)
+1: This is my preferred way pre .NET 4.0. Much more scalable than producing an entirely new array of strings from a list of ints so that String.Join(String, String[]) can be called. Only thing I'd say is that it's unusual to see this method written as an extension on String as opposed to IEnumerable<String> - I tend to always call it at the end of a long chain of extension method calls.Mcclimans
I stole the idea from Python if that is any help!Prowess
W
4

.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();
}
Winsome answered 31/8, 2010 at 15:43 Comment(4)
A good 2.0 approach. You might want to make the joining character a parameter rather than hardcoding it into the method.Heterotopia
A typical optimization is to append the delimiter without testing, then remove the last character once you get out of the loop.Leopoldeen
@Steven - I was thinking about it, but I think this would also depend on the length of the string (without testing I am unsure), so I stuck to the simple bool check.Winsome
I suspect the optimization would only be measurable for long strings. Having said that, I don't think it would be slower for even short ones.Leopoldeen
C
3

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

Cutlery answered 31/8, 2010 at 15:32 Comment(3)
Not sure I like this. IEnumerable<T> already has a Join method, and this new method performs a completely different operation, making its use counterintuitive. Secondly, if you were going to create this method, go ahead and make it generically applicable.Heterotopia
It's a hack mimicking the join method on arrays in Ruby. ruby-doc.org/core/classes/Array.html#M002182Pantechnicon
Also .ToString() does not always return a string representation of T so I guess that could really cause some confusion.Pantechnicon
K
2

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);
}
Knowing answered 31/8, 2010 at 15:24 Comment(1)
This is a decent approach if someone is still on 2.0. However, intArray is unnecessary. List<int> is indexable and has a Count property, making the conversion to an array superfluous. You also might want to make the joining character a parameter rather than hardcoding it into the method.Heterotopia
R
2

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);
    }
}
Rica answered 31/8, 2010 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.