C # net finds the shortest and longest line

Trying to find the longest and shortest line in a text file. The longest one returns correctly, but the shortest one is always empty, 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; } } 
+1
source share
3 answers

You set var Minimum = ""; , and since the length will be 0, it will never be longer than any line in the file. Set the first line to Minimum before the loop:

 var Minimum = lines[0]; 
+11
source

without using a loop.

 Maximum = lines.OrderByDescending(a => a.Length).First().ToString(); Minimum = lines.OrderBy(a => a.Length).First().ToString(); 
+3
source

Minimum.Length is initially 0. Ie

 Minimum.Length > line.Length 

will never become true, due to line.Length >= 0 for all lines.

Decision. You must initialize Mimimum first line before iteration.

+1
source

Source: https://habr.com/ru/post/989714/


All Articles