tags:

views:

405

answers:

6

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++)
    string += String.Format("{0}, ", list[iRow]);

returnValue = returnValue.Trim();

my output is

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

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

Thanks

+2  A: 

string's TrimEnd static method allows to specify which characters should be trimmed.

However, in your case it would make sense to check in the for loop whether you have empty slots, and at the end put together a resulting string with string.Join(string separator, string[] parts)

flq
+1  A: 

If you want to remove something you added, don't add them in the first place. Also, the StringBuilder type is better suited for concatenating multiple strings, as it much more memory efficient.

StringBuilder sb = new StringBuilder();

for (int i = 0; i < list.Count; i++)
{
    string rowValue = list[iRow];
    if (!string.IsNullOrEmpty(rowValue))
    {
        sb.Append(rowValue);
        sb.Append(", ");
    }    
}

// use sb.ToString() to obtain result
Cecil Has a Name
This code will produce an extra ", ", you should call sb.Remove(sb.Length - 2, 2) after the for loop.
Nescio
+6  A: 

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());
Miha Markic
+1 for nice-looking linq =)
Tomas Lycken
It is amazing how many things LINQ solves nicely.
Miha Markic
How did we ever code without LINQ?
Cameron MacFarland
+1  A: 

I hate to make assumptions, but I will because it seems you want preserve the "gaps" until you get to the end, in which case you should use TrimEnd. If not, then use any one of the other options to avoid adding the empty values in the first place.

More precisely if your output could look like:

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

Then you'll have to loop through and use TrimEnd.

Otherwise, if you can collapse the fields then exclude the empties upfront.

asd, aaa, qwe, 123123, somevalue

Nescio
+1  A: 
returnValue = returnValue.TrimEnd( ' ', ',' );
Akash Kava
The parameter on TrimEnd is a ParamArray you do not need a new char[] -- returnValue = returnValue.TrimEnd( ' ', ',' );
Nescio
@Nescio Thanks, i think in Split method I regularly use char array to strip empty values so I wrote here by mistake.
Akash Kava
A: 

try this:

List<string> list = new List<string>(
    new string[]{"asd", "aaa", "qwe", "123123", "", null, "", null, ""});
return String.Join(", ", list.Where(i => !String.IsNullOrEmpty(i)).ToArray());
Rubens Farias