Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of structures in .NET

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?
like image 467
Robin Rodricks Avatar asked Nov 17 '09 21:11

Robin Rodricks


People also ask

Which method is used to sort an array in Visual Basic?

You can sort the arrays in ascending order as well as descending . We can use Array. Sort method for sorts the elements in a one-dimensional array.

How do you sort an array?

We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class.

What is sorting in C#?

C# is using a default comparer method to sort integers numerically. The Sort method orders the integers in ascending order, while the Reverse method in descending order. $ dotnet run 0,1,2,3,4,5,7,8,9 9,8,7,5,4,3,2,1,0. The following example sorts integers with LINQ.


1 Answers

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);
like image 119
Fredrik Mörk Avatar answered Sep 19 '22 18:09

Fredrik Mörk