I've created a couple of Comparer classes for FileInfo objects to allow sorting by Name and LastWriteTime properties, but ideally I'd like to combine them into once class, so that I can compare/sort by any property simply by passing through the chosen property name.
However, I don't know how to go about this. My comparer class current includes:
Dim oX As FileInfo = CType(x, FileInfo)
Dim oY As FileInfo = CType(y, FileInfo)
Dim Result As Int16 = oX.Name.CompareTo(oY.Name)
I want to be able to substitute the Name property with the property name stored in the _sortColumn variable.
I'm expecting the solution to be rather simple, but as yet, I haven't been able to figure it out!
Solution:
I'd already got as far as researching Reflection, and had stumbled across PropertyInfo. But Fredriks solution cut down my search and provided a bit of structure, and I've come up with this (VB.Net) solution which seems to work nicely:
Dim oX_PI As PropertyInfo = CType(x, FileInfo).GetType.GetProperty(_sortColumn)
Dim oY_PI As PropertyInfo = CType(y, FileInfo).GetType.GetProperty(_sortColumn)
Dim Result As Int16 = oX_PI.GetValue(x, Nothing).CompareTo(oY_PI.GetValue(x, Nothing))
In reality, I have only have two columns to deal with so I could be slightly more explicit and t hus more performant. But this is a learning vehicle as much as it is a real-world problem so I've pursued this more sophisticated solution.