[英]C# comma separated string adds extra ending comma
我從窗體向MVC5 Controller傳遞了一串值,並使用C#將項目保存在數據庫的一個字段中。
string[]CarNotes
是通過控制器中的actionresult訪問的,並按以下方式操作:
string selection = "";
if (CarNotes != null && CarNotes.Length > 0)
{
foreach (string s in CarNotes)
{
selection += s + ", ";
}
}
然后,將選擇的內容保存在分配的數據庫字段中。 這很好。 唯一的問題是,它在列表的末尾添加了一個額外的“,”。 我如何防止出現這種多余的“,”。 謝謝
您也可以嘗試使用string.join ...
var selection = String.Join(", ", CarNodes);
更多信息在這里... https://msdn.microsoft.com/zh-cn/library/57a79xd0(v=vs.110).aspx
連接字符串時,請始終使用StringBuilder:
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(',');
或者,您可以使用Substring
:
if (selection.EndsWith(", "))
{
selection = selection.Substring(0, selection.Length - 2);
}
或Remove
:
if (selection.EndsWith(", "))
{
selection = selection.Remove(selection.Length - 2);
}
除了String.Join,您還可以使用聚合(linq,在函數式編程中也稱為reduce)
var selection = CarNotes.Aggregate((i, j) => i + ", " + j);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.