I'm looking for the one liner here, starting with:
int [] a = {1, 2, 3};
List<int> l = new List<int>(a);
and ending up with
String s = "1,2,3";
I'm looking for the one liner here, starting with:
int [] a = {1, 2, 3};
List<int> l = new List<int>(a);
and ending up with
String s = "1,2,3";
String s = String.Join(",", a.Select(i => i.ToString()).ToArray());
string.Join(",", l.ConvertAll(i => i.ToString()).ToArray());
This is assuming you are compiling under .NET 3.5 w/ Linq.
string s = string.Join(",", Array.ConvertAll(a, i => i.ToString()));
or in .NET 4.0 you could try (although I'm not sure it will compile):
string s = string.Join(",", a);
int[] array = {1,2,3};
string delimited = string.Join(",", array);
Another way of doing it:
string s = a.Aggregate("", (acc, n) => acc == "" ? n.ToString() : acc + "," + n.ToString());
I know you're looking for a one liner, but if you create an extension method, all future usage is a one liner. This is a method I use.
public static string ToDelimitedString<T>(this IEnumerable<T> items, string delimiter)
{
StringBuilder joinedItems = new StringBuilder();
foreach (T item in items)
{
if (joinedItems.Length > 0)
joinedItems.Append(delimiter);
joinedItems.Append(item);
}
return joinedItems.ToString();
}
For your list it becomes: l.ToDelimitedString(",")
I added an overload that always uses comma as the delimiter for convenience.