views:

406

answers:

4

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 Name As String
    Dim MPH As Integer

    Sub New(ByVal _Name As String, ByVal _MPH As Integer)
        Name = _Name
        MPH = _MPH
    End Sub
End Structure

How do I sort the array on one variable / property of the structure?

Dim cars() as stCar = {new stCar("ford",10), new stCar("honda",50)}

cars.sort("MPH") // how do I do this?
+4  A: 

Assuming that the structure has a property called MPH:

cars = cars.OrderBy(Function(c) c.MPH)

Note: the above code was auto-converted from the following c# code (in case it contains errors):

cars = cars.OrderBy(c => c.MPH);
Fredrik Mörk
+2  A: 

I don't know VB.NET, but you should be able to do this my implimenting IComparer. Take a look at this example

http://www.java2s.com/Code/VB/Data-Structure/UseIComparertosortbydifferentproperties.htm

Alternativly you can also use Linq

Bob
+3  A: 

The easiest way to perform the sort would be to use LINQ to Objects.

Dim q = From c In cars Order By c.MPH Select c
mkedobbs
A: 

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.

Bob Mc
Applying a lexicographical sort order to a collection of numeric values isn't going to do what you want. It might work with most data sets, but you'll be surprised when your program puts a Lamborghini ahead of a Prius ["8" > "48"].
Brian