I have a list containing Client objects. I want to sort the list by using it's property name ascending or descending, which I already have in the code in viewstate : ViewState("PropertyName") and ViewState("Order")
Dim objList As List(Of Client) = Session("ClientList")
objList.Sort(ViewState("PropertyName") + " " + ViewState("Order"))
datarepeater.datasource = objList
How can I achieve this ?
Normally, if you knew the property with which you wanted to sort, you would be able to just do something like this:
clients.Sort(Function(x, y) x.Name.CompareTo(y.Name))
In the above example, I am, of course sorting on the Name property (I don't know what properties the Client class has, I'm just using it as an example.
However, since you don't know which property you are going to use until run-time, you'll need to do something more complicated. If you really want to use the actual property names of the class, you could use Reflection to retrieve the value of the property dynamically, for instance:
clients.Sort(Function(x, y)
Dim xProperty As PropertyInfo = x.GetType().GetProperty(ViewState("PropertyName").ToString)
Dim yProperty As PropertyInfo = y.GetType().GetProperty(ViewState("PropertyName").ToString)
Dim xValue As Object = xProperty.GetValue(x)
Dim yValue As Object = yProperty.GetValue(y)
Return xValue.ToString().CompareTo(yValue.ToString())
End Function)
To reverse the sort order, just multiply the return value by -1, or switch which object you are comparing to what. For instance:
If ViewState("Order") = "Ascending" Then
Return xValue.ToString().CompareTo(yValue.ToString())
Else
Return yValue.ToString().CompareTo(xValue.ToString())
End If
You can also use Linq (using the same general method proposed by Steven Doggart):
sorted = lst.OrderBy(Function(x) x.GetType().GetProperty(_strColumnName01).GetValue(x)). _
ThenBy(Function(x) x.GetType().GetProperty(_strColumnName02).GetValue(x)).ToList()
In my particular example, I needed to sort by two columns, but for just a single column:
sorted = lst.OrderBy(Function(x) x.GetType().GetProperty(_strColumnName01).GetValue(x)).ToList()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With