Removing trailing comma from CSV data

This is the code to add a comma after another number, but I want to remove the last comma:

str_MSISDN.Append("'" + _MSISDN[x].TrimStart() + "'" + ",");
+3
source share
5 answers

Instead of manually adding things, I suggest you use String.Joinone with which everything will be correct. You can use LINQ to trim values. For example:

string x = string.Join(",", _MSISDN.Select(x => "'" + x.TrimStart() + "'")
                                   .ToArray());

EDIT: A nicer version is available with MoreLINQ and ToDelimitedString:

string x = _MSISDN.Select(x => "'" + x.TrimStart() + "'")
                  .ToDelimitedString(",");
+12
source

You can do this using the method TrimEnd(when you finish adding):

str_MSISDN = str_MSISDN.ToString().TrimEnd(',');
+3
source

String.TrimEnd():

[your value] = str_MSISDN.ToString().TrimEnd(",".ToCharArray())
+2

- string.Join:

string str_MSISDN = string.Join(", ", _MSISDN);

(, _MSISDN - )

, :

string str_MSISDN = string.Join(", ", _MSISDN.Select(x=>x.TrimStart()).ToArray());

Note how you need to call .ToArray as the Join method wants the array not to be IEnumerable

+1
source

I would say do not add it in the first place, you have several options for this.

1) Use string.join

2) Rebuild your loop as follows

int i = 0;
if (_MSISDN.Length > 0)
{
    str_MSISDN.Append("'" + _MSISDN[i++].TrimStart() + "'")
    while( i < _MSISDN.Length )
        str_MSISDN.Append(",'" + _MSISDN[i++].TrimStart() + "'");
}
0
source

Source: https://habr.com/ru/post/1722983/


All Articles