7

I have a collection of string in C#. My Code looks like this:

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

What i want to do is to find the max length of string in that collection and store it in variable. Currently, i code this manually, like?

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

The code above does the work for me, but i am looking for some built in function in order to maintain efficiency, because there will thousand of line in myfile :(

Jame
  • 21,150
  • 37
  • 80
  • 107
  • AFAIK - there is no in-built function to do this. However they may be other ways to write the same thing. For ex. using LINQ or using the Max function.... Not directly related to C# but there was a thread on same topic in Python - you can read if for reference: http://stackoverflow.com/questions/1292630/how-to-open-a-file-and-find-the-longest-length-of-a-line-and-then-print-it-out – sajoshi Apr 08 '11 at 05:52

2 Answers2

17

A simpler way with LINQ would be:

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

Note that if you're using .NET 4, you don't need to read all the lines into an array first, if you don't 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.)

That will be more efficient in terms of memory, but fundamentally you will have to read every line from disk, and you will need to iterate over those lines to find the maximum length. The disk access is likely to be the bottleneck of course.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

The efficiency will certainly not be worse in your case, if not better.

But if you're looking to be succinct, try lambdas with LINQ:

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

Btw, minor point: you can technically stop reading if the amount of data left is less than the longest line you've found. So you can technically save some steps, although it's probably not worth the code.


Completely irrelevant, but just because I feel like it, here's the (elegant!) Scheme version:

(reduce max (map length lines))
user541686
  • 205,094
  • 128
  • 528
  • 886