A personal repository of technical notes. - CSC

Array Sort C# Example

Example: How to sort an array of DirectoryInfo objects by Delegate and by Lambda Expression

// Get array of directories
DirectoryInfo tempTopDirectory = new DirectoryInfo("C:\\Temp1");
DirectoryInfo[] tempSubdirectories = tempTopDirectory.GetDirectories();

// Sort directories array by Name using delegate
Array.Sort(tempSubdirectories, delegate(DirectoryInfo x, DirectoryInfo y) { return x.Name.CompareTo(y.Name); });

// Sort directories array by Name using lambda expression
Array.Sort(tempSubdirectories, (x, y) => x.Name.CompareTo(y.Name));

How to sort directories in descending order

// Sort descending by comparing "y" to "x" instead of "x" to "y".
Array.Sort(tempSubdirectories, (x, y) => y.Name.CompareTo(x.Name));

How to sort directories by creation date

// Sort by creation date time
Array.Sort(tempSubdirectories, (x, y) => x.CreationTime.CompareTo(y.CreationTime));


Array.Sort(T) Method (T[], Comparison(T)) (System)

Lambda Expressions (C# Programming Guide)