As you probably know, it's easy to sort an array in .NET using Array.Sort(). But what if you want to sort an array of structures on a particular field defined in the structure? It can be done, and what follows is the approach I took.
I created a structure to represent a file:
Private Structure SuccessFile
Public Name As String
Public Created As Date
Public Hidden As Boolean
End Structure
Then I created an array to hold a list of files (and of course, I populated the array, but I'll leave that code out):
Dim SuccessFiles(FileList.Count - 1) As SuccessFile
At this point I needed to sort the items in the array by the Created field. I tried Array.Sort(), but it threw an exception, so I went to MSDN.
The MSDN description of Array.Sort says:
"Sorts the elements in an entire one-dimensional Array using the IComparable interface implemented by each element of the Array."
That sounded like the array of structures could be sorted if the structure implemented the IComparable interface. Cool! .NET structures can implement interfaces, so this should work.
I modified my structure as follows, and the Array.Sort worked perfectly.
Private Structure SuccessFile
Implements IComparable
Public Name As String
Public Created As Date
Public Hidden As Boolean
Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
Return Me.Created.CompareTo(CType(obj, SuccessFile).Created)
End Function
End Structure
I hope you find this useful.