Converting Int Array to String

From Logic Wiki
Jump to: navigation, search


Convert an array of integers to a comma-separated string

if we have

int[] arr = new int[5] {1,2,3,4,5};

and we want this

string => "1,2,3,4,5"


.NET 4

string.Join(",", arr)

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))

or it can be done by using extension methods like this

 public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
 {
     return lst.ToDelimitedString(p => p, separator);
 }


 public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector, string separator = ", ")
 {
     return string.Join(separator, lst.Select(selector));
 }

So now just:

new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();