Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

string

c#

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?

like image 705
Code Commander Avatar asked Aug 31 '10 15:08

Code Commander


People also ask

How do you join a string in a list in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do you join a list into a string in Java?

In Java, we can use String. join(",", list) to join a List String with commas.

What does string Join do C#?

The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.

What is string join?

join() method concatenates the given elements with the delimiter and returns the concatenated string. Note that if an element is null, then null is added. The join() method is included in java string since JDK 1.8. There are two types of join() methods in java string.


2 Answers

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

  • String.Join<T>(String, IEnumerable<T>)

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

    return string.Join(",", a.Select(x => x.ToString()).ToArray()); 
like image 52
Mark Byers Avatar answered Oct 08 '22 04:10

Mark Byers


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!

like image 28
Deleted Avatar answered Oct 08 '22 02:10

Deleted