`转换列表与LT;字符串&GT;`以逗号分隔的字符串 [英] Convert `List<string>` to comma-separated string
问题描述
有没有转换的快捷方式列表&LT;串&GT;
来用逗号分隔的字符串
在C#
Is there a fast way to convert List<string>
to a comma-separated string
in C#?
我不喜欢这样,但也许有一个更快或更有效的方式?
I do it like this but Maybe there is a faster or more efficient way?
List<string> ls = new List<string>();
ls.Add("one");
ls.Add("two");
string type = string.Join(",", ls.ToArray());
PS:搜索这个网站,但大多数解决方案是Java或Python
PS: Searched on this site but most solutions are for Java or Python
推荐答案
在.NET 4中,你不需要 ToArray的()
通话 - 的 的string.join
超载接受的IEnumerable&LT; T&GT;
或只是的IEnumerable&LT;字符串方式&gt;
In .NET 4 you don't need the ToArray()
call - string.Join
is overloaded to accept IEnumerable<T>
or just IEnumerable<string>
.
有.NET 4之前做的可能更有效的方法,但你真的需要它们?这实际上是在你的code瓶颈?
There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?
您的可能的遍历目录,制定出最终的大小,分配的StringBuilder
完全正确的尺寸,然后执行加入自己。这将避免额外的阵列在建的没有理由 - 但它不会节省很多时间,这将是一个的很多的多个code
You could iterate over the list, work out the final size, allocate a StringBuilder
of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.
这篇关于`转换列表与LT;字符串&GT;`以逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!