ASP.NET C# Age passed by the url

Asked

Viewed 44 times

0

Next, I have a page that receives age parameters that may vary in quantity.

Example:

url/page.aspx?idade=x&idade=y&idade=z

My idea is to take all the ages passed by url and select only the largest, see the code below:

var idadePax = Request.QueryString["idade"];
var maxAge = idadePax.Max();

But if I pass 44, 50 and 80 for url, returns me as the highest number 8, like he doesn’t recognize the ten 80 only the first number as higher. I had tried to use

foreach(String n in idadePax) Int32.Parse(n)

to convert each field to a whole, but I couldn’t apply the logic of the larger one to that, if someone can give me a help or a hint about what I’m sinning at?

  • Whether you are using web Forms or mvc?

  • 1

    @Virgilionovic webform

1 answer

3


When a request is made as shown in your example it is returned in the line:

var idadePax = Request.QueryString["idade"]; 

a given text with values separated by comma, for example:

44,50,80

Then you need to separate the data (with the method Split that will break this text into a array) and with Linnum convert the data and catch the biggest with Max, example:

if (Request.QueryString["idade"] != null)
{
    var idades = Request.QueryString["idade"];
    var idadeMax = idades.Split(',').Select(x => Convert.ToInt32(x)).Max();
}

this code will only serve if the data is always number, was a way to describe that the return of your Request.QueryString returns a string with data separated by a comma.

A way of verifying whether the dice really is a number:

if (Request.QueryString["idade"] != null)
{
    var idadeMax = int.MinValue;
    var idades = Request.QueryString["idade"];
    var idadesSplit = idades.Split(',');
    foreach (var item in idadesSplit)
    {
        if (int.TryParse(item.ToString(), out int n))
        {
            if (n > idadeMax) idadeMax = n;
        }
    }                
}
  • 1

    Our javascript equal... @Virgilio Novic, just thank you! It worked perfect here. In case I was passing the entire string to the Max() method correct? ai when I use the split it turns into an array and ai is possible to check which age is higher. that’s it?

  • 1

    @Mshijo this ... I edited and put the link for additional readings.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.