Sort a List of Object in VB.NET

后端 未结 4 662
刺人心
刺人心 2020-11-30 03:31

I have a list of passengers(object) where it has a differents properties..

passenger.name
passenger.age
passenger.surname

And I want to sor

相关标签:
4条回答
  • 2020-11-30 04:16

    you must implement IComparer interface.

    In this sample I've my custom object JSONReturn, I implement my class like this :

    Friend Class JSONReturnComparer
        Implements IComparer(of JSONReturn)
    
        Public Function Compare(x As JSONReturn, y As JSONReturn) As Integer Implements    IComparer(Of JSONReturn).Compare
            Return String.Compare(x.Name, y.Name)
        End Function
    
    End Class
    

    I call my sort List method like this : alResult.Sort(new JSONReturnComparer())

    Maybe it could help you

    0 讨论(0)
  • 2020-11-30 04:22

    To sort by a property in the object, you have to specify a comparer or a method to get that property.

    Using the List.Sort method:

    theList.Sort(Function(x, y) x.age.CompareTo(y.age))
    

    Using the OrderBy extension method:

    theList = theList.OrderBy(Function(x) x.age).ToList()
    
    0 讨论(0)
  • 2020-11-30 04:24

    If you need a custom string sort, you can create a function that returns a number based on the order you specify.

    For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:

    Private Function sortpictures(s As String) As Integer
        If Regex.IsMatch(s, "FRONT") Then
            Return 0
        ElseIf Regex.IsMatch(s, "SIDE") Then
            Return 1
        ElseIf Regex.IsMatch(s, "CLASP") Then
            Return 2
        Else
            Return 3
        End If
    End Function
    

    Then I call the sort function like this:

    list.Sort(Function(elA As String, elB As String)
                      Return sortpictures(elA).CompareTo(sortpictures(elB))
                  End Function)
    
    0 讨论(0)
  • 2020-11-30 04:25

    try..

    Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry

    mylist = sortedList.ToList

    0 讨论(0)
提交回复
热议问题