簡體   English   中英

逗號未按預期從字符串中刪除

[英]comma not being removed as expected from string

我有一個MVC應用程序,需要將信息存儲到數據庫中。 我得到一個字符串值,例如

string a = "a,b,c";

然后我通過刪除逗號來分割字符串

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

現在,在保存到數據庫之前,我必須重新添加逗號,這就是我遇到的問題。 我可以添加逗號,但是我也不想在字符串的末尾添加一個逗號。 如果我執行TrimEnd(',')它將刪除每個逗號。 有人可以告訴我我要去哪里了。 我將逗號重新添加為:

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

請注意,由於必須先進行一些驗證,所以我必須先分割逗號,然后再保存到數據庫

預期結果應為例如

a,b,c

相反,我得到了

a,b,c,

更新-以下是Bruno Garcia回答后我在MVC應用程序中使用的代碼

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

嘗試:

string.Join(",", b);

這將在數​​組的每個項目之間添加一個“,”

您可以只使用String.Join嗎?

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

完整文檔: https : //msdn.microsoft.com/zh-cn/library/57a79xd0(v=vs.110).aspx

它可以做

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

根據您發布的代碼,這是我認為您需要的

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

這將以逗號分割Request.Form["location"]的值。 然后過濾掉包含“ false”作為子字符串的項目,最后用逗號將它們重新連接在一起。

因此,類似“ abc,def,blahfalseblah,xyz”的字符串將變為“ abc,def,xyz”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM