在C#中将数组列表转换为逗号分隔的字符串 [英] Convert Array List to Comma Separated String in C#

查看:615
本文介绍了在C#中将数组列表转换为逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using String.Join to attempt to turn an array list into a string that is comma separated, such as

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

我似乎无法使语法正常工作。

I can't seem to get the syntax working.

这就是我要尝试的:

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

你能帮我吗?

预先感谢您-

推荐答案

从变量名猜测( arrayList ),您就可以在其中找到 List< string []> 或类似的类型。

Guessing from the name of your variable (arrayList), you've got List<string[]> or an equivalent type there.

这里的问题是您要在数组上调用 ToString()
尝试以下操作:

The issue here is that you're calling ToString() on the array. Try this instead:

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

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

If arrayList is simply an ArrayList containing strings, you can just do

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

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

Personally I would avoid using nongeneric collections (such as ArrayList) if possible and use strongly-typed collections from System.Collections.Generic such as List<string>. For example, if you have a piece of code that depends on that all contents of the ArrayList are strings, it will suffer catastrophically if you accidentally add an item that's not a string.

编辑2:如果您的 ArrayList 实际上包含 System .Web.UI.WebControls.ListItem 就像您在注释中提到的那样: arrayList.AddRange(ListBox.Items); ,那么您将需要改用以下代码:

EDIT 2: If your ArrayList actually contains System.Web.UI.WebControls.ListItems like you mentioned in your comment: arrayList.AddRange(ListBox.Items);, then you'll need to use this instead:

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

这篇关于在C#中将数组列表转换为逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆