在.NET中对结构数组进行排序

Rob*_*cks 5 vb.net sorting data-structures

这是只有蜂巢头脑可以提供帮助的时代之一 - 没有多少Google-fu可以!

我有一系列结构:

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
Run Code Online (Sandbox Code Playgroud)

如何在结构的一个变量/属性上对数组进行排序?

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

cars.sort("MPH") // how do I do this?
Run Code Online (Sandbox Code Playgroud)

Fre*_*örk 14

假设该结构具有称为MPH的属性:

cars = cars.OrderBy(Function(c) c.MPH)
Run Code Online (Sandbox Code Playgroud)

注意:上面的代码是从以下c#代码中自动转换的(如果它包含错误):

cars = cars.OrderBy(c => c.MPH);
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用:cars = cars.OrderBy(Function(c)c.MPH).ToArray (2认同)

mke*_*bbs 5

执行排序的最简单方法是使用 LINQ to Objects。

Dim q = From c In cars Order By c.MPH Select c
Run Code Online (Sandbox Code Playgroud)