Q:

C# - Sort File. ReadLines IEnumerable without Memory Overhead? 

Is this possible? 
I have the following code to reduce the total amount of memory usage:
File. WriteAllLines(
    Path. Combine(Path. GetDirectoryName(file[0]), "(Sort A-Z) " + Path. GetFileName(file[0])),
    File. ReadLines(file[0]).OrderBy(s=>s)
);

(file[0] is the input file path). 
This reduces usage from ForEach's e.t.c reducing CPU usage aswell as memory usage (barely). 
Its also faster than using a Foreach. 
The issue however, is the .OrderBy(s=>s) causes it to load the entire thing into memory.  Its not as bad as normally loading it into memory, but it still rises quite a bit of memory. ( Im using a 80mb file). 
Is there some way to order the IEnumerable/Order by A->Z when saving to a file without using much memory? 
I know it sounds vague and unsure what im looking for, because I dont know myself. 
Running with .OrderBy(s=>s) on a 2.7 million line file:
https://i.imgur.com/rUyDeFJ.gifv
Running WITHOUT .OrderBy(s=>s) on a 2.7 million line file:
https://i.imgur.com/Ejbnuty.gifv
(You can see it finish)

A:

It is necessary for .OrderBy to load the entire contents into memory.  It would be impossible for it to work any other way. 
OrderBy receives an IEnumerable.  Therefore it receives items on at a time.  However, consider the scenario where the very last row needs to be sorted before the very first row.  This could only be achieved if the last row and first row were both in memory at the same time.  Consider the scenario where the entire input were already sorted in the reverse order.  Hopefully these examples show why it is necessary for OrderBy to load the entire contents into memory. 
Algorithms exist to partition data sets into individual partitions, on disk, then merge those partitions.  However, they are beyond the scope of the Linq OrderBy function. 
Internally OrderBy reads everything into a buffer array then performs a quicksort over it.  If you're feeling brave, refer to the reference source:
https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,2530
(It's scattered throughout this file, but lines 2534-2542 best illustrate this)

