开发者

string.Join For comma-separated values

With the help of string.join, we can split a comma-separate开发者_开发知识库d 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.


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.

Edit:

var data = (List<MyClass>) (ComboBox1.DataSource);
string line = string.Join(",",  data.Select(x => x.Name) );


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/


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜