Get the highest value from a list?

Asked

Viewed 4,984 times

1

I need to generate 100 random values, save to a list (List<>) and catch the most number.

How do I get the most numbers?

  • I’m voting to close this question as out of scope because it’s like "do my homework for me"

  • It really looks like this @Thiagolunardi, but it’s not out of scope because it talks about programming. Maybe because it’s too open to opinions.

3 answers

3

You will use the function Max() read more here example:

List<int> lista = new List<int>{1,2,3,4,5,6,7,8,9,10};
int maiorValor = lista.Max();
Debug.WriteLine(maiorValor); //10

2

Using Linq, just call:

int maiorNumero = MinhaLista.Max();

1

Using only C#:

// criar a lista
var lista = new long[100];
for(var i = 0; i < 100; i++) 
    // Cada segundo possui 10 milhoes de Ticks, 
    // isso ira gerar valores aleatorios para a lista
    lista[i] = DateTime.Now.Ticks; 

// corre a lista
long maiorValor = 0;
for(var i = 0; i < 100; i++)
    // se o valor atual da lista for maior que o valor que já tenho
    if(lista[i] > maioValor)
        // atualiza o valor que ja tenho
        maiorValor = lista[i];      
  • I think it could be less complicated, I could use the Random class and then use the LINQ extensions to get the most value. Both are native to C#.

  • 1

    Yes, certainly, all the other answers were like that. But I’m interpreting that the question was asked by a super beginner, who is learning programming logic, and not just wanting to use c#, understand?

  • And Latin is native to the NET framework.

Browser other questions tagged

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