1

I have the following code:

 DrExistingData = myCommand.ExecuteReader();
                    if (DrExistingData.HasRows)
                     {
                        string participant = "";
                        string participants = "";

                         while (DrExistingData.Read())
                         {
                             participant = DrExistingData["Name"].ToString();
                             participants = participant + " , " + participants; 

                         }

                             Participant.Text = participants;
                       }

Participant is a textbox which is showing the list of names separated by commas but the problem is that the last name is also followed by a comma like:

Simren,Preety,jyoti, i want to remove the last comma from this list. Please help

4

4 回答 4

7

在您的 TextBox 文本上使用string.TrimEnd 。

Participant.Text = participants.TrimEnd(',');
于 2013-04-26T07:31:07.213 回答
6

最有效的方法是对第一个值进行特殊处理 - 还要注意我StringBuilder在循环中使用而不是字符串连接(这对于分配来说非常残酷):

var builder = new StringBuilder();
if(DrExistingData.Read()) {
    builder.Append(DrExistingData["Name"]);
    while(DrExistingData.Read()) {
        builder.Append(',').Append(DrExistingData["Name"]);
    }
}
Participant.Text = builder.ToString();
于 2013-04-26T07:32:24.440 回答
5

作为做你的东西的另一种方法是使用string.Join

var participants = new List<string>();
while (DrExistingData.Read())
{
    participants.Add(DrExistingData["Name"].ToString());
}
Participant.Text = string.Join(",", participants);
于 2013-04-26T07:33:09.640 回答
0

在.Net 4中你可以做

var drExistingData = myCommand.ExecuteReader();
participants.Text = string.Join(", ", 
                                drExistingData.Cast<IDataRecord>()
                                              .Select(record => record["Name"].ToString()));

对于 .Net 3.5 及更早版本,您必须添加.ToArray()

var drExistingData = myCommand.ExecuteReader();
participants.Text = string.Join(", ", 
                                drExistingData.Cast<IDataRecord>()
                                              .Select(record => record["Name"].ToString())
                                              .ToArray());
于 2013-04-26T07:40:36.613 回答