lundi 3 avril 2017

Sort a list by a function results

I want to sort a list by the results of functions that are contained in list items. How would go about doing that?

Here is an example. Let's say I have a following object:

Public Class MyListObject
    Public MyText1 As String
    Public MyText2 As String

    Public Function AddSuffix(ByVal MySuffix As String) As String
        Return Mytext1 & MySuffix
    End Function

End Class

(massively oversimplified for the sake of example)

After that I have a list of these objects:

Dim ResultList As New List(Of MyListObject)

Now, for example, to sort the list by the field MyText1 value, I used this:

ResultList = ResultList.OrderBy(Function(x) GetType(MyListObject).GetField("MyText1").GetValue(x)).ToList

(used reflection, so I can pass the field name as a string)

How can I sort this list by the function AddSuffix result and simultaneously pass the parameter MySuffix?

I imagine it would look something like this, but obviously this doesn't work

ResultList = ResultList.OrderBy(Function(x) GetType(MyListObject).GetField("AddSuffix(""_myCustomSuffix"")").GetValue(x)).ToList

PS. I realize, that in this example the function is pretty much meaningless. The actual code is much more complex and that function does return different sortable data for each list item.





Aucun commentaire:

Enregistrer un commentaire