Take the 2-minute tour ×

With the help of string.join, we can split a comma-separated list of values.

string.join(",", array)

Can I do the same for a CheckboxList data source? I have a DataValueField for this and need a comma-separated values without doing iteration.

share|improve this question
Something's gonna have to do the iteration; might as well be you. –  Roger Lipscombe Sep 13 '11 at 8:35
You mean string.Join(",", (IEnumerable<object>)checkboxlist.DataSource)? –  Gabe Sep 13 '11 at 8:36
Why do you need do it without iteration? string.join iterates too, has to!. –  Miserable Variable Sep 13 '11 at 8:36
@Roger, #Hemal, String.Join iterates and takes care of the last-one different issue, well worth using. –  Henk Holterman Sep 13 '11 at 9:18
add comment

3 Answers

up vote 5 down vote accepted

Yes, in Fx4 there is an overload of String.Join() that takes an IEnumerable<string>.

But it depends on what the DataSource property actually points to, roughly:

string line = string.Join(",",  ComboBox1.DataSource.Select(x => x.Name) );

You may need a different lambda, and some typecasting of DataSource.


var data = (List<MyClass>) (ComboBox1.DataSource);
string line = string.Join(",",  data.Select(x => x.Name) );
share|improve this answer
I have a class and the return type of the datasource is List<MyClass>. So how should i do with it ? –  abcdefghi Sep 13 '11 at 8:44
The OP says it's a List<MyClass>, but there is really no point in casting to it, cast to IEnumerable<MyClass> will obviously suffice –  Dyppl Sep 13 '11 at 8:53
Yes, but if you know for sure it's a List<> you should always check. –  Henk Holterman Sep 13 '11 at 8:54
add comment

Could make use of the little known CommaDelimitedStringCollection to make life easier ...

using System.Configuration;

var strList = new CommaDelimitedStringCollection();
strList.AddRange(ComboBox1.DataSource.Select(x => x.Name.ToString()));
var commaListStr = strList.ToString();

More info here ... http://www.idevforfun.com/index.php/2010/02/07/comma-delimited-lists/

share|improve this answer
add comment

The string.Join() solutions obviously work, if you feel like LINQ-ing you can also Aggregate the comma separated values string:

var list = (List<MyClass>)(ComboBox1.DataSource);
string commaSeparatedValues = list.Select(v => v.Name).Aggregate((current, next) => string.Concat(current, ",", next));

Just be aware of possible performance hits when handling large amounts of strings like this.

share|improve this answer
add comment

Your Answer


