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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With