在 C# 中将数组列表转换为逗号分隔的字符串

本文关键字:分隔 字符串 转换 数组 列表 | 更新日期: 2023-09-27 17:57:08

我正在使用 String.Join 尝试将数组列表转换为逗号分隔的字符串,例如

xxx@xxx.com,yyy@xxx.com,zzz@xxx.com,www@xxx.com

我似乎无法让语法工作。

这是我正在尝试的:

    for (i = 0; i < xxx; i++)
    {
        MailingList = arrayList[i].ToString();
        MailingList = string.Join(", ", MailingList.ToString());
        Response.Write(MailingList.ToString());
    }

你可以帮我吗?

提前谢谢你——

在 C# 中将数组列表转换为逗号分隔的字符串

从变量的名称(arrayList)猜测,你有List<string[]>或等效的类型。

这里的问题是您在数组上调用ToString()。试试这个:

for (i = 0; i < xxx; i++)
{
    var array = arrayList[i];
    MailingList = string.Join(", ", array);
    Response.Write(MailingList);
}

编辑:如果arrayList只是一个包含字符串的ArrayList,你可以做

Response.Write(string.Join(", ", arrayList.OfType<string>()));

就个人而言,如果可能的话,我会避免使用非泛型集合(例如ArrayList),并使用来自System.Collections.Generic(如List<string>)的强类型集合。例如,如果您有一段代码依赖于ArrayList的所有内容都是字符串,那么如果您不小心添加了不是字符串的项,它将遭受灾难性的影响。

编辑2:如果您的ArrayList实际上包含您在评论中提到的System.Web.UI.WebControls.ListItemarrayList.AddRange(ListBox.Items);,那么您需要改用以下内容:

Response.Write(string.Join(", ", arrayList.OfType<ListItem>()));

String.Join的第二个参数必须是IEnumerable。将MailingList.ToString()替换为arrayList,它应该可以工作。

初始化:

string result = string.Empty;

对于值类型:

if (arrayList != null) {
   foreach(var entry in arrayList){
      result += entry + ',';
   }
}

对于引用类型:

if (arrayList != null) {
   foreach(var entry in arrayList){
      if(entry != null)
         result += entry + ',';
   }
}

和清理:

if(result == string.Empty)
   result = null;
else
   result = result.Substring(0, result.Length - 1);
大多数

答案已经存在,仍然发布完整的工作片段

string[] emailListOne = { "xxx@xxx.com", "yyy@xxx.com", "zzz@xxx.com", "www@xxx.com" };
string[] emailListTwo = { "xxx@xxx1.com", "yyy@xxx1.com", "zzz@xxx1.com", "www@xxx1.com" };
string[] emailListThree = { "xxx@xxx2.com", "yyy@xxx2.com", "zzz@xxx2.com", "www@xxx.com" };
string[] emailListFour = { "xxx@xxx3.com", "yyy@xxx3.com", "zzz@xxx3.com", "www@xxx3.com" };
List<string[]> emailArrayList = new List<string[]>();
emailArrayList.Add(emailListOne);
emailArrayList.Add(emailListTwo);
emailArrayList.Add(emailListThree);
emailArrayList.Add(emailListFour);
StringBuilder csvList = new StringBuilder();
int i = 0;
foreach (var list in emailArrayList)
{
   csvList.Append(string.Join(",", list));
   if(i < emailArrayList.Count - 1)
      csvList.Append(",");
   i++;
}
Response.Write(csvList.ToString());