Sort an array of structures in .NET

前端 未结 7 1224
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 07:02

This is one of those times when only the hive mind can help - no amount of Google-fu can!

I have an array of structures:

Structure stCar 
    Dim Nam         


        
7条回答
  •  隐瞒了意图╮
    2020-12-16 07:08

    Another possibility, that doesn't use Linq but instead uses the .Net Array class' Sort method:

    Module Module1
        Structure stCar
            Dim Name As String
            Dim MPH As String
    
            Sub New(ByVal _Name As String, ByVal _MPH As Integer)
                Name = _Name
                MPH = _MPH
            End Sub
        End Structure
    
        Class CarCompareMph : Implements IComparer
    
            Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
                Dim xCar As stCar = DirectCast(x, stCar)
                Dim yCar As stCar = DirectCast(y, stCar)
                Return New CaseInsensitiveComparer().Compare(xCar.MPH, yCar.MPH)
            End Function
        End Class
    
        Sub Main()
            Dim cars() As stCar = {New stCar("honda", 50), New stCar("ford", 10)}
            Array.Sort(cars, New CarCompareMph)
    
            For Each c As stCar In cars
                Console.WriteLine("{0} - {1} MPH", c.Name, c.MPH)
            Next
        End Sub
    
    End Module
    

    I'm not sure if that's what you're looking for, but it's another approach.

提交回复
热议问题