Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a IList<int> collection to a comma separated list

Tags:

c#

ilist

Any elegant ways of converting a IList collection to a string of comma separated id's?

"1,234,2,324,324,2"

like image 233
mrblah Avatar asked Oct 07 '09 00:10

mrblah


4 Answers

    IList<int> list = new List<int>( new int[] { 1, 2, 3 } );
    Console.WriteLine(string.Join(",", list));
like image 137
Ed S. Avatar answered Nov 19 '22 15:11

Ed S.


You can do:

// Given: IList<int> collection;

string commaSeparatedInts = string.Join(",",collection.Select(i => i.ToString()).ToArray());
like image 35
Reed Copsey Avatar answered Nov 19 '22 14:11

Reed Copsey


// 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();
like image 20
strickland Avatar answered Nov 19 '22 16:11

strickland


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);
like image 41
Simon Fox Avatar answered Nov 19 '22 15:11

Simon Fox