[英]adding string to a List<string> with razor
I need to add an array of strings in TempData["scripts"], but first I need to see if the string already exist... If it exist don't add it... else add it to the array. 我需要在TempData [“ scripts”]中添加字符串数组,但是首先我需要查看字符串是否已经存在...如果存在,则不要添加它...否则将其添加到数组中。
This is what I have so far... It add the strings to the array... but I need to check the Tempdata first so it doesn't take duplicates... 这就是我到目前为止所拥有的...它将字符串添加到数组中...但是我需要先检查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
}
Assuming TempData["scripts"]
is an IEnumerable<string>
, you can do this more simply: 假设
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);
There's no need to check for duplicates this way. 无需通过这种方式检查重复项。
I wanted to be able to pass the path as an argument so I don't have to repeat it twice every time 我希望能够将路径作为参数传递,所以我不必每次都重复两次
@{
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.