In my opinion, you need to understand some points for deciding what is the best way.
First, let's think that we want to solve the problem with LINQ. Then, to write the most optimized code, you must understand Deferred Execution. Most Linq methods, such as Select
, Where
, OrderBy
, Skip
, Take
and some others uses DE. So, what is Deferred Execution? It means that, these methods will not be executed unless the user doesn't need them. These methods will just create iterator. And this iterator is ready to be executed, when we need them. So, how can user make them execute? The answer is, with the help of foreach
which will call GetEnumerator
or other Linq methods. Such as, ToList()
, First()
, FirstOrDefault()
, Max()
and some others.
These process will help us to gain some performance.
Now, let's come back to your problem. File.ReadLines
will return IEnumerable<string>
, which it means that, it will not read the lines, unless we need them. In your example, you have twice called sorting method for this object, which it means that it will sort this collection over again twice. Instead of that, you can sort the collection once, then call ToList()
which will execute the OrderedEnumerable
iterator and then get first and last element of the collection which physically inside our hands.
var orderedList = lines
.OrderBy(a => a.Length) // This method uses deferred execution, so it is not executed yet
.ToList(); // But, `ToList()` makes it to execute.
var Maximum = orderedList.Last();
var Minimum = orderedList.First();
BTW, you can find OrderBy
source code, here.
It returns OrderedEnumerable
instance and the sorting algorithm is here:
public IEnumerator<TElement> GetEnumerator()
{
Buffer<TElement> buffer = new Buffer<TElement>(source);
if (buffer.count > 0)
{
EnumerableSorter<TElement> sorter = GetEnumerableSorter(null);
int[] map = sorter.Sort(buffer.items, buffer.count);
sorter = null;
for (int i = 0; i < buffer.count; i++) yield return buffer.items[map[i]];
}
}
And now, let's come back to another aspect which effects the performance. If you see, Linq uses another element to store sorted collection. Of course, it will take some memory, which tells us it is not the most efficent way.
I just tried to explain you how does Linq work. But, I am very agree with @Dotctor as a result to your overall answer. Just, don't forget that, you can use File.ReadAllLines
which will not return IEnumerable<stirng>
, but string[]
.
What does it mean? As I tried to explain in the beginning, difference is that, if it is IEnumerable
, then .net will read line one by one when enuemrator enumerates over iterator. But, if it is string[]
, then all lines in our application memory.