tags:

views:

933

answers:

6

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

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

+8  A: 
    IList<int> list = new List<int>( new int[] { 1, 2, 3 } );
    Console.WriteLine(string.Join(",", list.Select( i => i.ToString() ).ToArray( )));
Ed Swangren
Doesn't work. ForEach() is defined on List<T>, not IList<T>.
Reed Copsey
It wasmy mistake, corrected
Ed Swangren
It was wrong anyway, not sure why I wrote ForEach...
Ed Swangren
+5  A: 

You can do:

// Given: IList<int> collection;

string commaSeparatedInts = string.Join(",",collection.Select(i => i.ToString()).ToArray());
Reed Copsey
+2  A: 

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);
Simon Fox
+3  A: 
// 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();
mstrickland
A good choice, I've always found StringBuilder to be a much faster at concatenation. Especially useful if the size of the list is BIG!
Alastair Pitts
StringBuilder.SubString doesn't exist, what you want is StringBuilder.ToString(int startIndex, int length)
Trillian
A: 
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);
Abhijeet Patel
It would be helpful if the person down voting an answer would leave a comment as to why it was down voted.This is a perfectly legitimate solution to the problem!
Abhijeet Patel
Yes, legitimate, just not the most simple way to do it. The ranking system is simply about getting the best answers to the top.
Ed Swangren
I would imagine that an answer would get down voted only if it is either incorrect, inaccurate or lacks details. Most of the answers posted here using LINQ are not necessarily "simple"!
Abhijeet Patel
I agree with you Abhijeet. Voting up is for ranking. Voting down is for incorrect. I set you back to 0.
Evildonald
A: 

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