.NET 4+
(.NET 4+)
IList<string> strings = new List<string>{"1","2","testing"};
string joined = string.Join(",", strings);
Detail & Pre .Net 4.0 Solutions
(详细信息和Pre .Net 4.0解决方案)
IEnumerable<string>
can be converted into a string array very easily with LINQ (.NET 3.5):
(使用LINQ(.NET 3.5)可以非常轻松地将IEnumerable<string>
转换为字符串数组:)
IEnumerable<string> strings = ...;
string[] array = strings.ToArray();
It's easy enough to write the equivalent helper method if you need to:
(如果需要,可以很容易地编写等效的辅助方法:)
public static T[] ToArray(IEnumerable<T> source)
{
return new List<T>(source).ToArray();
}
Then call it like this:
(然后像这样称呼它:)
IEnumerable<string> strings = ...;
string[] array = Helpers.ToArray(strings);
You can then call string.Join
.
(然后你可以调用string.Join
。)
Of course, you don't have to use a helper method: (当然,你不必使用一个辅助方法:)
// C# 3 and .NET 3.5 way:
string joined = string.Join(",", strings.ToArray());
// C# 2 and .NET 2.0 way:
string joined = string.Join(",", new List<string>(strings).ToArray());
The latter is a bit of a mouthful though :)
(后者虽然有点满口:))
This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) this one .
(这可能是最简单的方法,并且性能也非常高 - 还有其他问题,关于性能是什么样的,包括(但不限于) 这个 。)
As of .NET 4.0, there are more overloads available in string.Join
, so you can actually just write:
(从.NET 4.0开始, string.Join
有更多的重载,所以你实际上可以写:)
string joined = string.Join(",", strings);
Much simpler :)
(更简单:))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…