mrblah
mrblah

Reputation: 103497

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

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

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

Upvotes: 6

Views: 9987

Answers (6)

Ed Swangren
Ed Swangren

Reputation: 124642

    IList<int> list = new List<int>( new int[] { 1, 2, 3 } );
    Console.WriteLine(string.Join(",", list));

Upvotes: 16

opherko
opherko

Reputation: 141

mstrickland has a good idea on using string builder because of its speed with larger lists. However, you can't set a stringbuilder as a string. Try this instead.

    var strBuilder = new StringBuilder();

    foreach (var obj in list)
    {
        strBuilder.Append(obj.ToString());
        strBuilder.Append(",");
    }

    return strBuilder.ToString(0, strBuilder.Length - 1); 

Upvotes: 0

Abhijeet Patel
Abhijeet Patel

Reputation: 6868

List<int> intList = new List<int>{1,234,2,324,324,2};
var str = intList.Select(i => i.ToString()).Aggregate( (i1,i2) => string.Format("{0},{1}",i1,i2));
Console.WriteLine(str);

Upvotes: 0

Simon Fox
Simon Fox

Reputation: 10561

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);

Upvotes: 3

strickland
strickland

Reputation: 1993

// 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();

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564383

You can do:

// Given: IList<int> collection;

string commaSeparatedInts = string.Join(",",collection.Select(i => i.ToString()).ToArray());

Upvotes: 5

Related Questions