生成逗号分隔值 [英] Generating Comma Separated Values
本文介绍了生成逗号分隔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有字符串的集合:
Suppose I have a collection of strings:
"foo"
"bar"
"xyz"
和我想生成从列表中逗号分隔值成是这样的:
And I would like to generate a comma separated values from the list into something like:
"foo, bar, xyz"
请注意缺乏,结尾。
Notice the lack of ", " at the end.
据我所知,有许多方法可以产生这样的:
I am aware that there are dozens of ways to generate this:
- 使用for循环和的String.Format()或StringBuilder的。
- 使用整数计数器并删除结束,如果值> 0
- 请不要把,在第一次运行
- 等
样品code:
if (strs.Count() > 0)
{
var sb = new StringBuilder();
foreach (var str in strs)
sb.AppendFormat("{0}, ", str);
return sb.Remove(0, 2).ToString();
}
什么是最好的code是对于上述方案高度可重用的,为什么?
What is the best code that is highly reusable for the above scenario, and why?
推荐答案
的string.join是正确的答案,但在一个IEnumerable的情况下,LINQ的往往比for循环更短:
String.Join is the right answer, but in the case of an IEnumerable, Linq is often shorter than a for loop:
someStringCollection.Aggregate((first, second) => first + ", " + second);
这篇关于生成逗号分隔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文