Сортировать массив структур в .NET - PullRequest
5 голосов
/ 18 ноября 2009

Это один из тех случаев, когда только улей может помочь - никакое количество Google-фу не может!

У меня есть массив структур:

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

Как отсортировать массив по одной переменной / свойству структуры?

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

cars.sort("MPH") // how do I do this?

Ответы [ 7 ]

14 голосов
/ 18 ноября 2009

Предполагая, что структура имеет свойство MPH:

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

Примечание: приведенный выше код был автоматически преобразован из следующего кода C # (в случае, если он содержит ошибки):

cars = cars.OrderBy(c => c.MPH);
4 голосов
/ 18 ноября 2009

Самый простой способ выполнить сортировку - использовать LINQ to Objects.

Dim q = From c In cars Order By c.MPH Select c
2 голосов
/ 18 ноября 2009

Я не знаю VB.NET, но вы должны быть в состоянии сделать это, мой важный IComparer. Взгляните на этот пример

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

Альтернативно вы также можете использовать Linq

1 голос
/ 23 октября 2014

Мне кажется, что простой способ работать в vb.net 2013 таков:

cars.Sort(Function(c1,c2) c1.MPH.CompareTo(c2.MPH))
1 голос
/ 18 ноября 2009

Еще одна возможность, которая не использует Linq, а вместо этого использует метод сортировки класса .Net Array:

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

Я не уверен, что это то, что вы ищете, но это другой подход.

0 голосов
/ 25 октября 2015

В VB.Net VS2015 есть еще один метод сортировки:

cars.Sort(New Comparison(Of stCar)(Function(x, y) 'x and y are of type of stCar
                                                             If x.MPH > y.MPH Then
                                                                 Return 1 ' Return Value>0 means x>y
                                                             End If
                                                             If x.MPH < y.MPH Then
                                                                 Return -1 ' Return Value<0 means x<y
                                                             End If
                                                             If x.MPH = y.MPH Then
                                                                 Return 0 ' Return Value=0 means x=y
                                                             End If
                                                         End Function))
0 голосов
/ 19 марта 2015
Public Class Form1
    Public Structure EstruturaPessoa
        Dim nome As String
        Dim idade As Integer
    End Structure

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim nome(,) As String = {{"Milton Inácio Pozza", 30}, _
                                 {"Araci Moraes", 34}, _
                                 {"Marli Lipi Jesus", 21}, _
                                 {"Gerson Guebur", 45}, _
                                 {"Marli Ulths", 72}, _
                                 {"Mauro Jesus Nadolni", 56}, _
                                 {"Cristiano Kobashikawa Ferreira", 44}, _
                                 {"Débora Nadolni", 90}, _
                                 {"Samanta Gomes Guebur", 66}, _
                                 {"Miguel Barbosa", 42}, _
                                 {"Luis Jesus", 24} _
                                }
        Dim Pessoa As EstruturaPessoa
        Dim ListaPessoa = New List(Of EstruturaPessoa)
        Dim i As Integer

        'Load ListaPessoa
        For i = 0 To (nome.Length / 2) - 1
            Pessoa.nome = nome(i, 0)
            Pessoa.idade = nome(i, 1)
            ListaPessoa.Add(Pessoa)
        Next i

        'Fill the ListView1 with the ListaPessoa before sorting
        For Each item_pessoa In ListaPessoa
            With Me.ListView1
                .Items.Add(item_pessoa.nome)
                With .Items(.Items.Count - 1).SubItems
                    .Add(item_pessoa.idade)
                End With
            End With
        Next

        'Sort ListaPessoa
        ListaPessoa.Sort(Function(c1, c2) c1.nome.CompareTo(c2.nome))

        'Modifiy the 6th item of ListaPessoa
        Pessoa = ListaPessoa(5)
        Pessoa.nome += " ***"   'Acrescenta asteriscos ao nome
        Pessoa.idade = 99       'Modifica a idade para 99
        ListaPessoa(5) = Pessoa 'Atualiza o item na ListaPessoa

        'Fill ListView2 with the ListaPessoa after sorting
        For Each item_pessoa In ListaPessoa
            With Me.ListView2
                .Items.Add(item_pessoa.nome)
                With .Items(.Items.Count - 1).SubItems
                    .Add(item_pessoa.idade)
                End With
            End With
        Next
    End Sub
End Class
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...