Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple char types from end of string

Tags:

string

c#

I have a loop that builds up address fields, some of these fields may be empty at the end of the string

List<string> list = new List<string>();

//list can contain any number of values, some of which might be "" (empty string)

string returnValue = "";
for (int iRow = 1; iRow <= list.Count; iRow++)
    returnValue += String.Format("{0}, ", list[iRow]);

returnValue = returnValue.Trim();

my output is

asd, aaa, qwe, 123123, , , , , 

How can i remove the trailing ", " from the string?

like image 522
Adriaan Stander Avatar asked Oct 10 '09 10:10

Adriaan Stander


2 Answers

returnValue = returnValue.TrimEnd(' ', ',');
like image 130
Akash Kava Avatar answered Sep 21 '22 04:09

Akash Kava


You should also avoid using strings in your case, instead use StringBuilder. Avoid also using senseles formatting -just list[iRow] is a better option.

Try something like this instead:

string result = string.Join(", ", 
                  list.Where(s => !string.IsNullOrEmpty(s)).ToArray());
like image 23
Miha Markic Avatar answered Sep 21 '22 04:09

Miha Markic