如何从数组列表创建逗号分隔的字符串?

我在一个处理脚本中存储了一个 ID 的 ArrayList,我想以逗号分隔的列表的形式输出到调试日志中。有没有什么方法能让我不用循环就能轻松得到这些信息呢?

编辑: 感谢乔尔指出的名单(T) ,可在。净值2.0及以上。如果你有的话,事情就简单多了。

144417 次浏览

Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:

...in VB.NET:

String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String()))

...in C#

string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String")))

The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.

EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!

String.Join(",", TargetList.ToArray())

Something like:

String.Join(",", myArrayList.toArray(string.GetType()) );

Which basically loops ya know...

EDIT

how about:

string.Join(",", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString));
foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

string.Concat(foo.ToArray().Select(a => a += ",").ToArray())

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

The solutions so far are all quite complicated. The idiomatic solution should doubtless be:

String.Join(",", x.Cast(Of String)().ToArray())

There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:

Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String())))

mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf keyword. Also, Convert.ToString is rather inefficient (lots of unnecessary internal evaluations) and the Convert class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.

Here's a simple example demonstrating the creation of a comma delimited string using String.Join() from a list of Strings:

List<string> histList = new List<string>();
histList.Add(dt.ToString("MM/dd/yyyy::HH:mm:ss.ffff"));
histList.Add(Index.ToString());
/*arValue is array of Singles */
foreach (Single s in arValue)
{
histList.Add(s.ToString());
}
String HistLine = String.Join(",", histList.ToArray());

string.Join(" ,", myArrayList.ToArray()); This will work with .net framework 4.5

So far I found this is a good and quick solution

//CPID[] is the array
string cps = "";
if (CPID.Length > 0)
{
foreach (var item in CPID)
{
cps += item.Trim() + ",";
}
}
//Use the string cps