简体   繁体   English

从列表C#中删除最后一个逗号或定界符

[英]Removing last comma or delimiter from the list c#

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. Simren,Preety,jyoti,我想从此列表中删除最后一个逗号。 Please help 请帮忙

在您的文本框文本上使用string.TrimEnd

Participant.Text = participants.TrimEnd(',');

The most efficient way to do this is to special-case the first value - also noting that I'm using a StringBuilder rather than string-concatenation in a loop (which is pretty brutal for allocations): 执行此操作的最有效方法是对第一个值进行特殊大小写-还要注意我在循环中使用StringBuilder而不是字符串连接(对于分配而言这是很残酷的):

var builder = new StringBuilder();
if(DrExistingData.Read()) {
    builder.Append(DrExistingData["Name"]);
    while(DrExistingData.Read()) {
        builder.Append(',').Append(DrExistingData["Name"]);
    }
}
Participant.Text = builder.ToString();

As another way to do your stuff is to use string.Join : 另一种方法是使用string.Join

var participants = new List<string>();
while (DrExistingData.Read())
{
    participants.Add(DrExistingData["Name"].ToString());
}
Participant.Text = string.Join(",", participants);

In .Net 4 you can do 在.Net 4中,您可以执行

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

For .Net 3.5 and earlier you must add an .ToArray() 对于.Net 3.5及更早版本,您必须添加.ToArray()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM