There is a List(of FileInfo)
in which I have the properties of 4 pdf files. The list should be arranged so that the cover letter is at index 0, the curriculum vitae at index 1, the certificates at index 2 and another sheet at index 3. I know that the cover letter is added last, it is (before sorting) therefore at index 3. I've done that intentionally.
The names of the 3 files (the CV, the certif., the other sheet) are always the same.
My question is: is there a nice way to sort the items?
Sorting automatically can only be done if there is some property of the objects that can be compared to determine which is considered lesser and which is considered greater. That can be done automatically with numbers, dates, text and any other type that implements the IComparable
and/or IComparable(Of T)
interface. If there is no such property then you can still perform your own manual comparisons in a Comparison(Of T)
delegate or a class that implements IComparer
and/or IComparer(Of T)
. See my three-part blog post here for more details.
As an example, here's how you might do it with a Comparison(Of T)
delegate inline:
Dim files As List(Of FileInfo)
'...
files.Sort(Function(fi1, fi2)
Dim fileNames = {"The First File.pdf",
"The Second File.pdf",
"The Third File.pdf",
"The Fourth File.pdf"}
Return Array.IndexOf(fileNames, fi1.Name).CompareTo(Array.IndexOf(fileNames, fi2.Name))
End Function)
In that example, I have put the file names (which you say are constant) into an array, thus mapping them to numbers (the element indexes). Those numbers can then be compared to determine the relative order of any two items in the list. You could define a class that implemented IComparer(Of T)
(it's considered good practice to implement IComparer
as well and delegate the non-generic implementation to the generic implementation) and use the same logic in its Compare
method.