更新时间:2023-02-23 08:58:18
仅连接值,例如
The just concatenate the values, e.g.
ArrayList al = new ArrayList();
al.Add(5);
al.Add("foo");
al.Add(true);
string s="";
foreach (object o in al)
{
s += o.ToString();
}
如果您有很多项目,请考虑使用 StringBuilder [
If you have many items please consider using the StringBuilder[^] class.
好示例/en-us/library/ttw7t8t6(v=vs.80).aspx [
nice example on http://msdn.microsoft.com/en-us/library/ttw7t8t6(v=vs.80).aspx[^]
您可以在互联网上找到针对您案件的通用解决方案.
这是我发现的:
Hi,
You can find generic solution for your case on internet.
Here is what I found:
public static class ExtensionMethods
{
// for generic interface IEnumerable<t>
public static string ToString<t>(this IEnumerable<t> source, string separator)
{
if (source == null)
throw new ArgumentException("Parameter source can not be null.");
if (string.IsNullOrEmpty(separator))
throw new ArgumentException("Parameter separator can not be null or empty.");
string[] array = source.Where(n => n != null).Select(n => n.ToString()).ToArray();
return string.Join(separator, array);
}
// for interface IEnumerable
public static string ToString(this IEnumerable source, string separator)
{
if (source == null)
throw new ArgumentException("Parameter source can not be null.");
if (string.IsNullOrEmpty(separator))
throw new ArgumentException("Parameter separator can not be null or empty.");
string[] array = source.Cast<object>().Where(n => n != null).Select(n => n.ToString()).ToArray();
return string.Join(separator, array);
}
}
</t></t></t>
使用此扩展方法的示例:
Example of using this extension method:
ArrayList myArrayList = new ArrayList();
myArrayList.Add("Item1");
myArrayList.Add("Item2");
myArrayList.Add("Item3");
myArrayList.Add("Item4");
myArrayList.Add("Item5");
string myListAsString = myArrayList.ToString("; ");
输出:
Item1;项目2;项目3;项目4; Item5
Output:
Item1; Item2; Item3; Item4; Item5