C #: how to get the length of a string in a string []

I have a rowset in C #. My code is as follows:

string[] lines = System.IO.File.ReadAllLines(@"d:\SampleFile.txt"); 

What I want to do is find the maximum string length in this collection and save it in a variable. Am I currently encoding this manually, for example?

 int nMaxLengthOfString = 0; for (int i = 0; i < lines.Length;i++ ) { if (lines[i].Length>nMaxLengthOfString) { nMaxLengthOfString = lines[i].Length; } } 

The above code works for me, but I'm looking for some built-in function to maintain efficiency, because there will be thousands of lines in myfile :(

+7
source share
2 answers

A simple LINQ way would be:

 int maxLength = lines.Max(x => x.Length); 

Please note: if you are using .NET 4, you do not need to read all the lines into an array first, unless you need them later:

 // Note call to ReadLines rather than ReadAllLines. int maxLength = File.ReadLines(filename).Max(x => x.Length); 

(If you're not using .NET 4, it's easy to write the equivalent of File.ReadLines .)

It will be more efficient in terms of memory, but in principle you will have to read each line from disk, and you will need to iterate over these lines to find the maximum length. Of course, disk access is likely to be a bottleneck.

+17
source

Efficiency, of course, will not be worse in your case, if not better.

But if you want to be brief, try lambdas with LINQ:

 lines.Aggregate((a, b) => Math.Max(a.Length, b.Length)); 

Btw, a minor point: you can technically stop reading if the amount of data remaining is less than the longest line you found. This way you can technically save a few steps, although this is probably not worth the code.


It’s completely inappropriate, but only because I feel that this is an (elegant!) Version of the circuit:

 (reduce max (map length lines)) 
+3
source

All Articles