Any elegant ways of converting a IList collection to a string of comma separated id's?
"1,234,2,324,324,2"
IList<int> list = new List<int>( new int[] { 1, 2, 3 } );
Console.WriteLine(string.Join(",", list));
You can do:
// Given: IList<int> collection;
string commaSeparatedInts = string.Join(",",collection.Select(i => i.ToString()).ToArray());
// list = IList<MyObject>
var strBuilder = new System.Text.StringBuilder();
foreach(var obj in list)
{
strBuilder.Append(obj.ToString());
strBuilder.Append(",");
}
strBuilder = strBuilder.SubString(0, strBuilder.Length -1);
return strBuilder.ToString();
This will do it
IList<int> strings = new List<int>(new int[] { 1,2,3,4 });
string[] myStrings = strings.Select(s => s.ToString()).ToArray();
string joined = string.Join(",", myStrings);
OR entirely with Linq
string aggr = strings.Select(s=> s.ToString()).Aggregate((agg, item) => agg + "," + item);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With