Search major number of a List c #

0

Good Night,

I have to get the biggest number on a list and I do not know how to get it, I'm using 2 for to get it but I keep the last major I can not get it. This is my code:

static int get(int[] a)
    {
        int sort = 0;
        int sort2 = 0;
        int mayor = 0;
        List<int> a1 = new List<int>();
        foreach (int test in a)
        {
            a1.Add(test);
        }
        int cont = a1.Count;

        for (int i = 0; i < cont; i++)
        {
            for (int k = 0; k < cont; k++)
            {
                sort = a1[i];
                sort2 = a1[k];
                if (sort > sort2)
                {
                    mayor = sort;
                }
                else
                {
                    mayor = sort2;
                }
            }

        }

        return mayor;
    
asked by Hans 09.09.2017 в 04:29
source

2 answers

4

Good morning

In case you do not need the for that is not an exercise using that cycle add using System; and using System.Linq; and use the Max .

{
  List<int> a1 = new List<int>();
  /* Tu foreach donde llenas "a1" */

  return a1.Max();
}

Here you can see it better Max and Min

Of course, it is necessary to validate if you have data

    
answered by 09.09.2017 / 04:57
source
1

Ready,

The second for was too much, I only had to go back once and save the biggest one in my variable in the following way

             int sort = 0;
       // int sort2 = 0;
        int mayor = 0;
        List<int> a1 = new List<int>();
        foreach (int test in a)
        {
            a1.Add(test);
        }
        int cont = a1.Count;
        //AQUI ESTA LA OPERACION DE HAYAR EL NUMERO MAYOR
        for (int i = 0; i < cont; i++)
        {
            sort = a1[i];

            if (mayor > sort)
            {

            }
            else
            {
                mayor = sort;
            }

        }
        Console.WriteLine(mayor);

        return mayor;
    
answered by 09.09.2017 в 04:40