0

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.

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...

@{
        var scripts = (List<string>)TempData["scripts"];
        scripts.Add("../Scripts/test.js");
        scripts.Add("../Scripts/testv.js");
        scripts.Add("../Scripts/testh.js");
    }
1
  • 1
    can't you use if or just call .Distinct() afterwards? Commented Aug 28, 2015 at 19:17

3 Answers 3

1
@{
        var scripts = (List<string>)TempData["scripts"];
        if(scripts.Contains("../Scripts/test.js") == false)
        {
             scripts.Add("../Scripts/test.js");
        }
        //repeat with the others
    }
Sign up to request clarification or add additional context in comments.

2 Comments

this is great but I would need a function to pass "../Scripts/test.js" as an argument... because I may have 10 files to add...
this way I can have a list of filespath in an array and create a forloop to inject it... do you know what I mean?
0

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); }
        }
    }

Comments

0

Edit to reflect your answer

Assuming TempData["scripts"] is an IEnumerable<string>, you can do this more simply:

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.