2

Trying to find the longest and shortest line in a text file. Longest returns correct but the shortest is always blank, any ideas?

        var lines = System.IO.File.ReadLines(@"C:\test.txt");            
        var Minimum = "";
        var Maximum = "";


            foreach (string line in lines)
            {

                if (Maximum.Length < line.Length)
                {
                    Maximum = line;
                }


                if (Minimum.Length > line.Length)
                {
                    Minimum = line;
                }
           }
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
Zulake
  • 149
  • 3
  • 14

3 Answers3

12

You are setting var Minimum = ""; and as it's length will be 0, it will never be longer than any line in the file. Set the first line as the Minimum before the loop:

var Minimum = lines[0];
va.
  • 848
  • 3
  • 17
  • 39
4

without using loop..

Maximum = lines.OrderByDescending(a => a.Length).First().ToString();
Minimum = lines.OrderBy(a => a.Length).First().ToString();
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
  • 1
    Why do you sort twice, isn't the longest the first and shortest the last after the first sort? Also, sorting has a larger time complexity than one loop, so this solution has worse performance. It is easier to read though. – juunas Jun 25 '15 at 06:43
  • @juunas Do you have any reference that this type sorting for twice using lamda expression is slower than the for loop.. – sangram parmar Jun 25 '15 at 06:50
  • 3
    Any comparison sort has a time complexity of n log n. OPs loop is linear, thus it is faster. – juunas Jun 25 '15 at 06:52
1

Minimum.Length is initially 0. I.e.

Minimum.Length > line.Length

will never get true, because of line.Length >= 0 for all lines.

Solution: You should initialize Mimimum with the first line before iterating.

JimiLoe
  • 950
  • 2
  • 14
  • 22