Indeed; even the underlying Win32 API doesn't guarantee the order:
FindNextFileA function (fileapi.h) - Win32 apps | Microsoft Learn[^]:
The order in which this function returns the file names is dependent on the file system type. With the NTFS file system and CDFS file systems, the names are usually returned in alphabetical order. With FAT file systems, the names are usually returned in the order the files were written to the disk, which may or may not be in alphabetical order. However, as stated previously, these behaviors are not guaranteed.
However, it's probably still more efficient to use some sort of bounded sorted list to store the 10 "first" files based on your chosen sort order as they're enumerated, rather than getting the list of all files, sorting them, and then picking the "first" 10. :) Eg, using SortedList<TKey, TValue>, which unfortunately doesn't support an upper-bound on the number of elements:
const int NumberOfFiles = 10;
const int Capacity = NumberOfFiles + 1;
SortedList<string, string> firstFiles = new(Capacity, StringComparer.OrdinalIgnoreCase);
foreach (string filePath in Path.EnumerateFiles(directoryPath))
{
string fileName = Path.GetFileName(filePath);
firstFiles.Add(fileName, filePath);
if (firstFiles.Count == Capacity)
{
firstFiles.RemoveAt(firstFiles.Count - 1);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer