簡體   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