Izzy
Izzy

Reputation: 6866

comma not being removed as expected from string

I have an MVC app which I need to store information into the database. I get a string value e.g. as

string a = "a,b,c";

I then split the string by removing the commas as

string[] b = a.Split(',');

Now before I save to database I have to add the comma back in and this is where I'm kind of stuck. I can add the comma however one gets added to the end of the string too which I don't want. If I do TrimEnd(',') it removes every comma. Can someone tell me where I'm going wrong please. I'm adding the comma back as:

foreach(var items in b)
{
   Console.WriteLine(string.Format("{0},", items));
}

Please note I have to split the comma first due to some validation which needs to be carried out before saving to DB

The expected result should be for example

a,b,c

In stead I get

a,b,c,

Update - The below is the code I'm using In my MVC app after Bruno Garcia answer

string[] checkBoxValues = Request.Form["location"].Split(',');
foreach(var items in checkBoxValues)
{
   if (!items.Contains("false"))
   {
       UsersDto.Location += string.Join(",", items);
   }
 }

Upvotes: 1

Views: 127

Answers (4)

Bruno Garcia
Bruno Garcia

Reputation: 6398

Try:

string.Join(",", b);

This will add a ',' in between each item of your array

Upvotes: 4

juharr
juharr

Reputation: 32266

Based on the code you posted this is what I think you need

UsersDto.Location = string.Join(
    ",", 
    Request.Form["location"]
           .Split(',')
           .Where(item => !item.Contains("false")));

That will split the values in Request.Form["location"] on comma. Then filter out items that contain "false" as a substring, and finally join them back together with a comma.

So a string like "abc,def,blahfalseblah,xyz" would become "abc,def,xyz".

Upvotes: 1

Mostafiz
Mostafiz

Reputation: 7352

it can do

string[] checkBoxValues = Request.Form["location"].Split(',');
string s = "";
foreach (var items in checkBoxValues)
{
    if (!items.Contains("false"))
      {
        s = s + string.Format("{0},", items);
      }

}
UsersDto.Location = s.TrimEnd(',');

Upvotes: 1

Huy Hoang Pham
Huy Hoang Pham

Reputation: 4147

You can just use String.Join then?

var result = String.join(",", b); // a,b,c

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

Upvotes: 1

Related Questions