简体   繁体   中英

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 eg 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);
   }
 }

Try:

string.Join(",", b);

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

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

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(',');

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM