Diin
Diin

Reputation: 585

C# comma separated string adds extra ending comma

I pass a string of values from form to MVC5 Controller and save items in one field in database using the C#.

The string[]CarNotes is accessed with the actionresult in controller and manipulated as below:

string selection = "";
                if (CarNotes != null && CarNotes.Length > 0)
                {
                    foreach (string s in CarNotes)
                    {
                        selection += s + ", ";
                    }
                }

I then save the contents of selection in the assigned database field. This works fine. The only problem is that it adds an extra ',' at the end of the list. How can I prevent this extra ','. Thanks

Upvotes: 0

Views: 938

Answers (3)

rbtLong
rbtLong

Reputation: 1572

aside from String.Join, you can also use aggregate (linq, aka reduce in functional programming)

var selection = CarNotes.Aggregate((i, j) => i + ", " + j);

Upvotes: 0

rbtLong
rbtLong

Reputation: 1572

you can also try using string.join...

var selection = String.Join(", ", CarNodes);

more info here... https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx

Upvotes: 3

Jeremy Thompson
Jeremy Thompson

Reputation: 65654

Always use a StringBuilder when you're concatenating strings:

StringBuilder selection = new StringBuilder();
if (CarNotes != null && CarNotes.Length > 0)
{
   foreach (string s in CarNotes)
   {
      selection.Append(s);
      selection.Append(", ");
   }
}
//Trim the ending space, then trim the ending comma
return selection.ToString().TrimEnd().TrimEnd(',');

Alternatively you could use Substring:

if (selection.EndsWith(", "))
{
    selection = selection.Substring(0, selection.Length - 2);
}

Or Remove:

if (selection.EndsWith(", "))
{
    selection = selection.Remove(selection.Length - 2);
}

Upvotes: 1

Related Questions