Reputation: 22200
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 :(
Upvotes: 7
Views: 23908
Reputation: 210765
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))
Upvotes: 3
Reputation: 1503954
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.
Upvotes: 17