简体   繁体   English

string.Join用于逗号分隔的值

[英]string.Join For comma-separated values

With the help of string.join , we can split a comma-separated list of values. 借助string.join ,我们可以拆分以逗号分隔的值列表。

string.join(",", array)

Can I do the same for a CheckboxList data source? 我可以对CheckboxList数据源执行相同的操作吗? I have a DataValueField for this and need a comma-separated values without doing iteration. 我为此有一个DataValueField ,并且需要用逗号分隔的值而不进行迭代。

Yes, in Fx4 there is an overload of String.Join() that takes an IEnumerable<string> . 是的,在Fx4中, String.Join()的重载采用了IEnumerable<string>

But it depends on what the DataSource property actually points to, roughly: 但这大致取决于DataSource属性实际指向的内容:

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

You may need a different lambda, and some typecasting of DataSource. 您可能需要一个不同的lambda和一些数据源类型转换。

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 ... 可以利用鲜为人知的CommaDelimitedStringCollection使生活更轻松...

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/ 此处有更多信息... 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: string.Join()解决方案显然可以工作,如果您感觉像LINQ-ing,也可以聚合用逗号分隔的值字符串:

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. 请注意在处理这样的大量字符串时可能会影响性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM