C# 如何删除for循环中的逗号?

C# 如何删除for循环中的逗号?,c#,for-loop,C#,For Loop,我想删除第一个逗号。有没有办法去掉循环中的逗号 这是我的密码: foreach (var field in tablefields.Items) { if (m_datacount < datatype.Items.Count) { d_type = datatype.Items[m_datacount].ToString(); m_datacount++; } richTextBox1.Text = richTextBox

我想删除第一个逗号。有没有办法去掉循环中的逗号

这是我的密码:

foreach (var field in tablefields.Items)
{
    if (m_datacount < datatype.Items.Count)
    {
        d_type = datatype.Items[m_datacount].ToString();
        m_datacount++;
    }

    richTextBox1.Text = richTextBox1.Text + "\t,@" + field + " " + d_type + "\n";
    datatype.ResetText();
}

m_datacount = 0;

为什么要重新发明轮子……

只需使用
String.Join

string result = String.Join(", ", myarray);
例如

string[] myarray = { "Firstuser", "Seconduser" };
因此,
结果
将是
“Firstuser,Seconduser”

方法可用于从字符串中删除尾随字符:

richTextBox1.Text = richTextBox1.Text.TrimEnd(',');

您可以使用下面的代码

richTextBox1.Text = richTextBox1.Text.Substring(0,richTextBox1.Text.Length-1);

还可以查看删除最后一个索引。使用
删除(索引)

字段2的目的是什么?您的代码中没有使用它

如果使用foreach循环,为什么要使用计数器(m_fieldcount

什么是tablefields.ResetText() 无论如何,试试这个:

richTextBox1.Text = String.Join("\n\t,", tablefields.Items.Select(a=>a.ToString()).ToArray());

我会使用
String.Join
。由于您对另一个答案发表了评论,即
tablefields
是一个
ListBox
,因此此选项有效:

var strings = tablefields.Items.Cast<object>().Select(o => o.ToString());
richTextBox1.Text = String.Join(Environment.NewLine + ",", strings);
输出:

id
,spid
,charge_type_rcd
,name_e
,active_status
您还可以使用
StringBuilder
,它可读性较差,但如果您有很多很多项,则效率会更高:

StringBuilder sb = new StringBuilder();
foreach (var item in tablefields.Items)
    sb.AppendLine(item.ToString()).Append(',');
if (sb.Length > 0) sb.Length--;   // to remove the last comma
richTextBox1.Text = sb.ToString();

什么是
tablefields.Items
?你想展平的是你的收藏。OP的问题中没有
myarray
,这就是@TimSchmelter所说的。是的,我知道,但我得到的输出来自一个包含数据库数据的列表框。它删除了我所有的Com,因为数据来自数据库。顺便说一句:)@user3788757:这没关系,不是吗?我假设
列表框
包含
对象
,因此我使用
ToString
来创建字符串。请注意,我编辑了我的答案,以提供一种更有效的
StringBuilder
方法(如果您有1000多个条目)。@user3788757为什么?物品是什么类型的?
tablefields.Items.AddRange(new ListBox.ObjectCollection(tablefields, new[]{"id","spid","charge_type_rcd","name_e","active_status"}));
id
,spid
,charge_type_rcd
,name_e
,active_status
StringBuilder sb = new StringBuilder();
foreach (var item in tablefields.Items)
    sb.AppendLine(item.ToString()).Append(',');
if (sb.Length > 0) sb.Length--;   // to remove the last comma
richTextBox1.Text = sb.ToString();