Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 :(

like image 787
Jame Avatar asked Apr 08 '11 05:04

Jame


1 Answers

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.

like image 181
Jon Skeet Avatar answered Oct 13 '22 03:10

Jon Skeet