In my opinion, you need to understand some points in order to decide which is best.
First, think that we want to solve the LINQ problem. Then, to write the most optimized code, you must understand Delayed Execution . Most Linq methods, such as Select , Where , OrderBy , Skip , Take , and some others use DE. So what is delayed execution? This means that these methods will not be executed if the user does not need them. These methods will simply create an iterator. And this iterator is ready to execute when we need them. So how can the user execute them? The answer is with foreach , which is called by GetEnumerator or other Linq methods. For example, ToList() , First() , FirstOrDefault() , Max() and some others.
This process will help us get some performance.
Now back to your problem. File.ReadLines will return an IEnumerable<string> , which means that it will not read lines if we do not need them. In your example, you called the sort method twice for this object, which means that it will sort this collection twice. Instead, you can sort the collection once, and then call ToList() , which will execute the OrderedEnumerable iterator, and then get the first and last elements of the collection that are physically inside our hands.
var orderedList = lines .OrderBy(a => a.Length)
By the way, you can find OrderBy source code here .
It returns an 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 back to another aspect that affects performance. If you see, Linq uses another element to store the sorted collection. Of course, this will require some memory, which tells us that this is not the most efficient way.
I just tried to explain to you how Linq works. But, I very much agree with @Dotctor as a result of your general answer. Remember that you can use File.ReadAllLines , which will not return IEnumerable<stirng> , but string[] . What does it mean? As I tried to explain at the beginning, the difference is that if it is IEnumerable , then .net will read the lines one by one when the enuemrator enumerates the iterator. But if it is string[] , then all the lines in our application memory.