Supposed i have an array int[] arr = {1,2,3,4}
I want to convert it into a string. The result i want it to be like this string a = "1,2,3,4";
so can i have something "string a = arr...." to do it, instead of writing a for loop??
Thanks
Supposed i have an array int[] arr = {1,2,3,4}
I want to convert it into a string. The result i want it to be like this string a = "1,2,3,4";
so can i have something "string a = arr...." to do it, instead of writing a for loop??
Thanks
string result = string.Join(", ", arr.Select(item => item.ToString()).ToArray());
You can use String.Join:
int[] arr = new [] { 4, 5, 6, 7 };
string joined = String.Join(",", arr);
See http://msdn.microsoft.com/en-us/library/57a79xd0.aspx for more info.
As of .NET 4, you can simply do:
var result = string.Join( ",", arr );
In earlier versions,
var result = string.Join( ",", arr.Select( a => a.ToString() ).ToArray() );
If you can't use .net 4 (I can't yet as our customers don't deploy it), you can use an extension method. This will work then work for all IEnumerable<T>'s
with appropriately implemented .ToString() overrides. You can also pick what sort of seperator you want.
Once you have the below, you can just do string s = myenumerable.Seperated(",");
public static class EnumerableExtender
{
public static string Separated<T>(this IEnumerable<T> l, string separator)
{
var sb = new StringBuilder();
var first = true;
foreach (var o in l)
{
if (first) first = false; else sb.Append(separator);
sb.Append(o.ToString());
}
return sb.ToString();
}
}