Find the largest number in a text file

Asked

Viewed 88 times

-1

I’m trying to make a program that reads a text file and tells me the highest number in it.

Here’s what I got from the code:

while (sLine != null)
{
    sLine = objReader.ReadLine();
    if (sLine != null)
        arrText.Add(sLine);
}

objReader.Close();

foreach (string sOutput in arrText)
Console.WriteLine(sOutput);
Console.ReadLine();
  • What types of information does your text file contain? Only numbers? Does it have text as well? Is the information being stored by default? Show an example of your file please?

  • this one has only numbers

1 answer

5

You can read the file lines in a much easier way using File.ReadAllLines(). This method will read the file and create a array where each line in the file represents an element in the array.

After that just convert each row to number. The method Select maps each item of array of origin (the array returned by ReadAllLines, in this case) according to the function passed by parameter. The function there only converts each element (l represents each element) for number.

So, at the end of that, you have the array numeros with N elements (where N is the number of lines in the file), where each element is the numerical representation of each line in the initial file.

After that just look for the largest number on array.

This can be found using LINQ, with the method Max.

// using System.Linq; <<-- Inclua isto nos using

var numeros = File.ReadAllLines(caminhoArquivo).Select(l => Convert.ToInt32(l)).ToArray();
var maior = numeros.Max(n => n);
Console.WriteLine($"O maior número no arquivo é {maior}");

For the purpose of understanding, the above code is equivalent to this

var linhas = File.ReadAllLines(caminhoArquivo);

var numeros = new List<int>();
foreach(var l in linhas)
    numeros.Add(Convert.ToInt32(l));

int maior = 0;
foreach(var numero in numeros)
    maior = numero > maior ? numero : maior;

Console.WriteLine($"O maior número no arquivo é {maior}");

Browser other questions tagged

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