繁体   English   中英

将字符串添加到列表 <string> 用剃刀

[英]adding string to a List<string> with razor

我需要在TempData [“ scripts”]中添加字符串数组,但是首先我需要查看字符串是否已经存在...如果存在,则不要添加它...否则将其添加到数组中。

这就是我到目前为止所拥有的...它将字符串添加到数组中...但是我需要先检查Tempdata,以便它不会重复...

@{
        var scripts = (List<string>)TempData["scripts"];
        scripts.Add("../Scripts/test.js");
        scripts.Add("../Scripts/testv.js");
        scripts.Add("../Scripts/testh.js");
    }
@{
        var scripts = (List<string>)TempData["scripts"];
        if(scripts.Contains("../Scripts/test.js") == false)
        {
             scripts.Add("../Scripts/test.js");
        }
        //repeat with the others
    }

编辑以反映您的答案

假设TempData["scripts"]IEnumerable<string> ,则可以更简单地执行此操作:

var scripts = (HashSet<string>)TempData["scripts"];
string[] path = {
    "../Scripts/jquery-flot/jquery.flot.js",
    "../Scripts/jquery-flot/jquery.flot.time.min.js",
    "../Scripts/jquery-flot/jquery.flot.selection.min.js",
    "../Scripts/jquery-flot/jquery.flot.animator.min.js",
    "../Scripts/jquery-sparkline/jquery-sparkline.js"
};

foreach (var item in path)
    scripts.Add(item);

无需通过这种方式检查重复项。

我希望能够将路径作为参数传递,所以我不必每次都重复两次

 @{
        var scripts = (List<string>)TempData["scripts"];
        string[] path = {
            "../Scripts/jquery-flot/jquery.flot.js",
            "../Scripts/jquery-flot/jquery.flot.time.min.js",
            "../Scripts/jquery-flot/jquery.flot.selection.min.js",
            "../Scripts/jquery-flot/jquery.flot.animator.min.js",
            "../Scripts/jquery-sparkline/jquery-sparkline.js"
        };
        foreach (var item in path)
        {
            if (scripts.Contains(item) == false) { scripts.Add(item); }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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