0

I'm write this function:

public static String QueryString(string queryStringKey)
{
    if (HttpContext.Current.Request.QueryString[queryStringKey] != null)
    {
        if (HttpContext.Current.Request.QueryString[queryStringKey].ToString() != string.Empty)
            return HttpContext.Current.Request.QueryString.GetValues(1).ToString();
    }
    return "NAQ";
}

And i want to get just one value from querystring parameter. for example i send "page" to my function and url is: "sth.com/?page=1&page=2" and function return to me: "1,2" ; but i want first value: "1", How?

2 Answers2

1

GetValues returns a string[] if the key exists. An array is zero based, so you get the first element by using array[0], you are using GetValues(1) in your code, i assume that you wanted the first.

You could also use the Enumerable.First extension method:

Request.QueryString.GetValues("page").First();  

Since GetValues returns not an empty array but null if the key was not present you need to check that explicitely (FirstOrDefault doesn't work):

public static String QueryString(string queryStringKey)
{
    if (HttpContext.Current != null && HttpContext.Current.Request != null)
    {
        string[] values = HttpContext.Current.Request.QueryString.GetValues("queryStringKey");
        if (values != null) return values.First();
    }
    return "NAQ";
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

A better approach would be -

public static String QueryString(string queryStringKey)
{

    if (HttpContext.Current!=null && HttpContext.Current.Request!=null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[queryStringKey])
    {
        return HttpContext.Current.Request.QueryString.GetValues(queryStringKey).First();
    }
    return "NAQ";
}
Vandesh
  • 6,368
  • 1
  • 26
  • 38
  • Why is it better? You need to check the return value of `GetValues` anyway since it doesn't return an empty array but `null`. So this approach won't work even if it uses `FirstOrDefault`. Edited [my answer](http://stackoverflow.com/a/18357336/284240) accordingly. – Tim Schmelter Aug 21 '13 at 12:46
  • Firstly - A better approach I meant in answer to the original question. Second - Agree with you on `null` thing but wouldn't it be already considered if we have a null check in place in the if condition above? – Vandesh Aug 21 '13 at 12:53
  • 1
    Correct, the `if` should handle the case even if it would be better to check for `null` explicitely since the value could also be an empty string(then `NAQ"` would be returned even if the key exists). So `FirstOrDefault` is just confusing since it can never be an empty array. – Tim Schmelter Aug 21 '13 at 12:56