2014-07-01 49 views
-1

我想刪除第一個逗號。有沒有辦法刪除循環的逗號?如何在for循環中刪除逗號?

這裏是我的代碼:

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; 

輸出:

,@id uniqueidentifier 
,@title varchar 
,@active_flag bit 
,@created_by_id uniqueidentifier 
,@created_by_system_code varchar 
,@created_date_time datetime 
,@modified_by_id uniqueidentifier 
,@modified_by_system_code varchar 
,@modified_date_time datetime 
+2

什麼是'tablefields.Items'? –

回答

2

Why reinvent the wheel....

只需使用String.Join

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

用於例如

string[] myarray = { "Firstuser", "Seconduser" }; 

所以result將是"Firstuser, Seconduser"

+3

什麼是myarray? –

+0

其你的收藏你想要扁平化。 –

+0

OP在他的問題中沒有「myarray」,這就是@TimSchmelter所說的。 – Abbas

0

TrimEnd方法可用於從字符串刪除尾隨字符:

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

它刪除了所有我昏迷 – user3788757

0

您可以使用下面menioned代碼

richTextBox1.Text = richTextBox1.Text.Substring(0,richTextBox1.Text.Length-1); 
-1
richTextBox1.Text + "" + t_fields + "\n\t,".Remove(richTextBox1.Text.Lenght - 1); 

檢出也刪除最後一個索引。使用Remove(index)

0

什麼是場2的目的是什麼?這是不是在你的代碼中使用...

爲什麼如果您使用的是foreach循環使用一個計數器(m_fieldcount)?

什麼是tablefields.ResetText();呢?

不管怎樣,試試這個:

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

的數據列表框選擇來將無法正常工作 – user3788757

+0

@ user3788757爲什麼呢?項目是什麼類型? – Arie

+0

其從數據庫 – user3788757

2

我會用String.Join。既然你談到另一個答案是tablefieldsListBox這個工程:

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

這個樣本數據進行測試:

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這是可讀性較差,但如果您有許多項目可以更高效:

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(); 
+0

將數據從一個數據庫來BTW。 :) – user3788757

+0

@ user3788757:那沒關係,是嗎?我認爲'ListBox'包含'Objects',因此我使用'ToString'來創建字符串。請注意,我編輯了我的答案,提供了一個可以更高效的「StringBuilder」方法(如果您說有超過1000個項目)。 –

+0

好的謝謝,所以現在我會把代碼放在哪裏? – user3788757