如何对结构数组进行排序?

时间:2015-09-25 23:24:56

标签: arrays vb.net list sorting

我有一个结构数组。 它被宣布为这样

Public SongsList as New List(Of Song)

"宋"它的结构名称。 它有2个变量:路径和名称; 我想知道如何按名称对这个数组进行排序。

Public Structure Song
  Public Path as String
  Public Name as String
End Structure

我试过这个

ListBox1.Items.Clear()
Dim sorted = SongsList.OrderBy(Function(s) s.Name).ToList 
Dim i As Integer 
For i = 0 To sorted.Count - 1
    ListBox1.Items.Add(sorted(i).Name.ToString) 
Next

但它会抛出一个NullReferenceException

这就是我向SongsList添加项目的方式

Dim open As New OpenFileDialog
open.Title = "Add songs"
open.Filter = "MP3 Files(*.mp3)|*.mp3"
open.Multiselect = True
ListBox1.Items.Clear()
If open.ShowDialog = DialogResult.OK Then
    For Each SelectedSong As String In open.FileNames
        i += 1
        Dim songToAdd As New Song
        songToAdd.Path = SelectedSong.ToString
        songToAdd.Name = GetSafeFileName(SelectedSong.ToString)
        SongsList.Add(songToAdd)
        ListBox1.Items.Add(SongsList(i).Path)
    Next
End If

2 个答案:

答案 0 :(得分:0)

您可以使用Lambda表达式。它使用您在OrderBy函数中选择的字段。让我们覆盖ToString方法告诉列表框要显示什么,然后你可以将列表设置为数据源。

班级:

Public Class Song
  Public Property Path as String
  Public Property Name as String
  Public Overrides Function ToString() As String
    Return Me.Path
  End If
End Class

用法:

Dim open As New OpenFileDialog
open.Title = "Add songs"
open.Filter = "MP3 Files(*.mp3)|*.mp3"
open.Multiselect = True
If open.ShowDialog = DialogResult.OK Then
  For Each SelectedSong As String In open.FileNames
    Dim songToAdd As New Song
    songToAdd.Path = SelectedSong
    songToAdd.Name = GetSafeFileName(SelectedSong.ToString)
    SongsList.Add(songToAdd)
   Next
End If
Listbox1.DataSource = SongsList.OrderBy(Function(s) s.Name).ToList

答案 1 :(得分:0)

*非常类似于OneFineDay的答案......

您不需要自定义类,只需使用List(Of FileInfo)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim open As New OpenFileDialog
    open.Title = "Add songs"
    open.Filter = "MP3 Files(*.mp3)|*.mp3"
    open.Multiselect = True
    If open.ShowDialog = DialogResult.OK Then
        ListBox1.DataSource = Nothing
        Dim songs As New List(Of FileInfo)
        For Each SelectedSong As String In open.FileNames
            songs.Add(New FileInfo(SelectedSong))
        Next
        songs = songs.OrderBy(Function(fi) fi.Name).ToList
        ListBox1.DataSource = songs
        ListBox1.DisplayMember = "Name"
        ListBox1.ValueMember = "FullName"
    End If
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If ListBox1.SelectedIndex <> -1 Then
        Dim fi As FileInfo = DirectCast(ListBox1.SelectedItem, FileInfo)
        Dim name As String = fi.Name
        Dim fullPath As String = fi.FullName
        Debug.Print("name = " & name)
        Debug.Print("fullPath = " & fullPath)
    End If
End Sub