c#列表中的最后一项

时间:2013-04-07 11:02:47

标签: c# arrays list

我需要在文章和文章中突出显示关键字或标签。将变量传递给jQuery Array 我正在使用属性将值从C#传递到java脚本,这也适用于我需要格式化我在数据库中存储的关键字,如one, two, three, four, five,six,seven

为了使其工作,我必须用单'或双引号"包装每个关键字。

JQuery的

    function HighlightKeywords(keywords) {
        var el = $("body");
        $(keywords).each(function () {
            var pattern = new RegExp("(" + this + ")", ["gi"]);
            var rs = "<a href='search.aspx?search=$1'<span style='background-color:#FFFF00;font-weight: bold;background-color:#FFFF00;'>$1</span></a>";
            el.html(el.html().replace(pattern, rs));
        });
    }

HighlightKeywords(["<%= MyProperty %>]");

C#代码

string _sFinalList = null;

protected string MyProperty { get { return _sFinalList; } }
string sKewords = "one, two, three, four, five,six,seven";

List<string> lstKewords = sKewords.Split(',').ToList();
foreach (string list in lstKewords) // Loop through List with foreach
{
   _sFinalList += "'" + list + "',";

}

此代码出现问题的原因是,在最后一句话后,我想知道在最后一句话之后避免添加,的最佳方法的广告,

当前输出:&#34;&#39;一个&#39;,&#39;两个&#39;,&#39;三个&#39;&#39;四&# 39;,&#39;五,&#39;六&#39;七,&#39;&#39;

所需的输出:&#34;&#39;一个&#39;,&#39;两个&#39;三个&#39;四个&#39;四个&# 39;,&#39;五,&#39;六&#39;&#39;七&#39;&#34;

赞赏这方面的帮助

4 个答案:

答案 0 :(得分:3)

在C#中,使用String.Join()

List<string> lstKeywords = sKeywords.Split(',').ToList();

var quotedKeywords = lstKeywords.Select(s => "'" + s + "'");

string _sFinalList = string.Join(",", quotedKeywords);

答案 1 :(得分:1)

您可以使用String.Join()

string sKewords = "one, two, three, four, five,six,seven";
List<string> lstKewords = sKewords.Split(',').ToList();
var _partial = lstKewords.Select(x => "'" + x + "'");
Var _result = String.Join(",", _partial);

答案 2 :(得分:1)

您可以使用String.Join

var result = string.Format("'{0}'", string.Join("','", yourList));

答案 3 :(得分:0)

完成for循环后,您可以简单地使用字符串类的子字符串函数删除lastIndexOf(“,”)。

OR

如果循环不在最后一次迭代中,你可以在for循环中添加if语句并添加“,”。

相关问题