C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
OrderByDescending: The OrderByDescending call is more complex. It receives a Func argument—this is an anonymous method.
Func: The Func method is created with anonymous method syntax. The Function receives a string (the file name) and returns its length.
So: The OrderByDescending method sorts the files by their lengths. We then convert its result (an IEnumerable) into an array with ToArray.
ToArrayVB.NET program that sorts files by size
Imports System.IO
Module Module1
Sub Main()
' The target directory.
Dim dir As String = "C:\\programs"
' Get files.
Dim files() As String = Directory.GetFiles(dir)
' Order files from largest size to smallest size.
Dim sorted() As String = files.OrderByDescending(
New Func(Of String, Integer)(Function(fn As String)
Return New FileInfo(fn).Length
End Function)).ToArray
' Loop and display files.
For Each element As String In sorted
Console.WriteLine(element)
Console.WriteLine(New FileInfo(element).Length)
Next
End Sub
End Module
Output
C:\\programs\file.py
611
C:\\programs\file.rb
369
C:\\programs\file.php
235
C:\\programs\file.pl
184
Tip: This program is inefficient. If you built a data structure (a List of KeyValuePairs) you could avoid accessing FileInfo so many times.
ListKeyValuePair