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 🙁
A simpler way with LINQ would be:
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:
(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.