The file Final.txt contains student grades on a final exam. Write a program using LINQ that displays the average grade on the exam and the percentage of grades that are above average. The figure below shows a possible outcome of the program:
The figure below shows the contents of Final.txt which was used to obtain the above results. You can create this file yourself using Notepad.
Suggested Control Names and Attributes:
Name Property | Text Property | ReadOnly Property | Control Type | Notes |
frmAverageGrade | Grades | N/A | Form | Holds Controls |
btnEvaluate | Evaluate Grades | N/A | Button | Triggers event to display grade analysis |
txtAverageGrade | Set to true | TextBox | Displays average grade. | |
txtAboveAverage | Set to true | TextBox | Displays % of grades above average. |
Write the Code:
' Project: Average Grade ' Description: This program reads a list of grades from a text file. It uses LINQ to calculate ' and display the average grade and the percentage of grades that are above average. Public Class frmAverageGrade ' Declare global variables Dim tempGrades() As String = IO.File.ReadAllLines("Final.txt") Dim grades(tempGrades.Count - 1) As Double Private Sub btnEvaluate_Click(sender As Object, e As EventArgs) Handles btnEvaluate.Click ' Load grades from temporary string array into integer array Dim counter As Integer = 0 For Each grade As Integer In tempGrades grades(counter) = grade counter += 1 Next ' Place values into a query for easy manipulaton Dim gradeQuery = From grade In grades Select grade ' Calulate the average of the query and display it txtAverageGrade.Text = (gradeQuery.Average / 100).ToString("P") ' Determine how many grades are above average and calculate the percentage Dim gradeQuery2 = From grade In grades Where grade > gradeQuery.Average Select grade txtAboveAverage.Text = (gradeQuery2.Count / grades.Count).ToString("P") End Sub End Class