Visual Basic混乱

时间:2014-11-28 02:26:24

标签: vb.net

我被要求创建一个程序,要求我找到一个特定数组的最大值。我在这个项目中使用多个表单,并使用了用户定义的数据类型并在其下创建了多个数组。有一个与此相关的第一个表单,它定义了我定义的数据类型是gStudentRecord,定义它的数组是姓氏,Id和GPA。第二种形式是我编写所有代码以显示我想要的内容。我的问题是如何从该阵列中获取Max GPA。对不起,如果格式不是很好,这是我第一次使用Stackoverflow

Public Class frmSecond

  Private Sub frmSecond_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim Ctr As Integer
    Dim Line As String

    lstDisplay.Items.Clear()

    lstDisplay.Items.Add("Name".PadRight(25) & "ID".PadRight(16) & "GPA".PadRight(20) & "Out of state".PadRight(10))
    For Ctr = 0 To gIndex Step 1
        Line = gCourseRoster(Ctr).LastName.PadRight(20) & gCourseRoster(Ctr).ID.PadRight(15) & gCourseRoster(Ctr).GPA.ToString.PadRight(15) & gCourseRoster(Ctr).OutOfState.ToString().PadLeft(5)
        lstDisplay.Items.Add(Line)
    Next
  End Sub

  Private Sub btnStats_Click(sender As Object, e As EventArgs) Handles btnStats.Click
    Dim Ctr As Integer = 0
    Dim Average As Double
    Dim Sum As Double
    Dim Found As Boolean = False
    Dim Pass As Integer
    Dim Index As Integer

    lstDisplay.Items.Clear()

    **For Ctr = 0 To gIndex Step 1
        If gCourseRoster(Ctr).GPA > gCourseRoster(Ctr).GPA Then

            lstDisplay.Items.Add(gCourseRoster(Ctr).GPA)
        End If
    Next**

    Average = gComputeAverage(Sum)

    lstDisplay.Items.Add("Number of Students: " & gNumberOfStudents)
    lstDisplay.Items.Add("Average: " & Average)

  End Sub
  Private Function gComputeAverage(Sum As Double) As Double
    Dim Ctr As Integer
    Dim Average As Double

    For Ctr = 0 To gIndex Step 1
        Sum = Sum + gCourseRoster(Ctr).GPA
    Next

    Average = Sum / gNumberOfStudents
    Return Average
  End Function

End Class

1 个答案:

答案 0 :(得分:0)

您可以使用Lambda表达式来取笑它。 Cast部分通过将gCourseRoster提供给Double语句,从GPA转换为Select的集合。

Dim gList As New List(Of gCourseRoster)
gList.Add(New gCourseRoster With {.id = 1, .name = "Bob", .GPA = 3.9})
gList.Add(New gCourseRoster With {.id = 2, .name = "Sarah", .GPA = 3.2})
gList.Add(New gCourseRoster With {.id = 3, .name = "Frank", .GPA = 3.1})
Dim maxGPA = gList.Cast(Of gCourseRoster).Select(Function(c) c.GPA).ToList.Max
MessageBox.Show(maxGPA.ToString)

Output: 3.9