How do I return the first value of a query string if it has multiple values?

Consider a URL like this:

http://host.com?q=1&o=2&q=1

      


If I run Request.QueryString["q"]

it I get the value twice.

If I run Request.QueryString["q"].FirstOrDefault().ToString()

I seem to get "2"

How do I return the first value of a query string if it has multiple values?

+3


source to share


3 answers


Not sure how Microsoft deals with this thing, I see that if we pass the same key with multiple values, then the .NET Framework treats the values ​​as comma separated strings.

i.e.

if the query is like "? q = 10 & o = 2 & q = 11"

then



Request.QueryString["q"] == "10,11"

      

the only way to get the first value is by separating it with a comma.

Request.QueryString["q"].Split(',')[0]

      

0


source


In case anyone has the same question. Try the following:Request.QueryString.GetValues("q")?.FirstOrDefault();



0


source


var count=0;
var twince=string.Empty;
foreach(var item in Request.QueryString["q"])
{
     twince=item;
     count++;
     if(count==2)
        break;
}

      

OR

var twince=Request.QueryString["q"].Split(',')[1];

      

OR

var first=QueryString["q"].FirstOrDefault;
var twince=Request.QueryString["q"].FirstOrDefault(frs=>frs!=first);

      

0


source







All Articles