使用namevaluecollection在数组中设置查询字符串

时间:2018-07-27 15:58:15

标签: c# arrays list foreach namevaluecollection

我的URL格式为:

workareaRefs=1&workareaRefs=2&workareaRefs=3&jurisdictions=1&jurisdictions=2&jurisdictions=4&tags=1&tags=2

等。如何将所有这些值存储为3个单独的数组作为对象?我将使用它们来过滤查询。下面的方法编写不正确。不知道该怎么做。

谢谢

    public (string[] workareaRefs, string[] jurisdictions, string[] tags) FiltersQS(NameValueCollection parameters)
    {
        var workAreaRefs = new List<string>();
        var jurisdictions = new List<string>();
        var tags = new List<string>();

        if (WorkAreas.Count == 0 && workAreaRefs.Count == 0)
        {
            foreach (var workAreaRef in parameters["workarearef"])
            {
                workAreaRefs.Add(workAreaRef);
            }
        }

        if (Jurisdictions.Count == 0 && jurisdictions.Count == 0 )
        {
            foreach (var jurisdiction in parameters["jurisdictionref"])
            {
                workAreaRefs.Add(jurisdiction);
            }
        }

        if (Tags.Count == 0 && tags.Count == 0)
        {
            foreach (var tags in parameters["tags"])
            {
                tags.Add();
            }
        }

        return (workAreaRefs, jurisdictions, tags);
    }

1 个答案:

答案 0 :(得分:0)

    //Why are you creating lists??? Why not just use the arrays which are passed
    //To your method???
    //You shouldn't be trying to declare local variables with
    //the same names as the parameters being passed to the method
    public (string[] workareaRefs, string[] jurisdictions, string[] tags) FiltersQS(NameValueCollection parameters)

    //Don't use the same names
    //for local variables as the names of parameters being passed to method
    //Changed the list variable names
    var workAreaRefs = new List<string>();
    var jurisDictions = new List<string>();
    var tagss = new List<string>();

    //Change your if statements
    //if (WorkAreas.Count == 0 && workAreaRefs.Count == 0) //NO
    if(workareaRefs.Length > 0) //Yes
    {
        foreach (var workAreaRef in parameters["workarearef"])
        {
            workAreaRefs.Add(workAreaRef);
        }

        //Could just use the method parameter
        //foreach (var workAreaRef in workareaRefs)
        //{
            //workAreaRefs.Add(workAreaRef);
        //}


    }

    //etc. Other ifs need modified like above