我有一个存储学生的程序'文本文件中的名称和分数。然后,我需要根据它们的分数按升序对此文本文件进行排序,并仅将前10个实现到表格布局面板中。我不确定使用什么功能来实现这一目标。
文本文件如下所示:
10,克莱尔 0,爱丽丝
5,鲍勃 8,希德
9,迪伦
1,安娜
6,丹
3,丽贝卡
4,布莱尔
2,乔治
7,乔
答案 0 :(得分:1)
您需要做的第一件事是将TableLayoutPanel添加到表单中。给它一列10行并给它一个名字。我将我命名为tlpScores
。
接下来,我们将介绍您需要做的事情。首先,创建一个类来保存分数对象。我打电话给我Scores
:
Private Class Scores
Public Property Name As String
Public Property Score As Integer
End Class
接下来,进入表格Load
活动并阅读分数:
' Change "C:\Scores\Scores.txt" to match wherever your file is located
Dim lines As String() = System.IO.File.ReadAllLines("C:\Scores\Scores.txt")
这会将文本文件读入数组。每行一个元素。
接下来,初始化一个新的空列表以存储我们Scores
对象的多个得分:
Dim scores As New List(Of Scores)
接下来,遍历我们读入的每一行并解析出名称和分数,并将其存储在Scores
对象中,并将该对象添加到我们的列表中:
For Each line As String In lines
If String.IsNullOrWhiteSpace(line) Then
Continue For
End If
Dim score As New Scores
score.Name = line.Split(","c)(1).Trim()
score.Score = CInt(line.Split(","c)(0))
scores.Add(score)
Next
接下来,我们可以使用Linq对列表进行排序,只选择前10名:
' Your question said Ascending, but I'm assuming you want the top 10.
' If you truly did mean ascending, then change OrderByDescending to
' OrderBy
Dim topTenScores = scores.OrderByDescending(Function(z) z.Score).Take(10)
最后,将它们添加到TableLayoutPanel:
For Each score As Scores In topTenScores
Dim label As New Label
label.Text = score.Name & " --> " & score.Score
tlpScores.Controls.Add(label)
Next
这是完整的程序:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lines As String() = System.IO.File.ReadAllLines("c:\q\scores.txt")
Dim scores As New List(Of Scores)
For Each line As String In lines
If String.IsNullOrWhiteSpace(line) Then
Continue For
End If
Dim score As New Scores
score.Name = line.Split(","c)(1).Trim()
score.Score = CInt(line.Split(","c)(0))
scores.Add(score)
Next
Dim topTenScores = scores.OrderByDescending(Function(z) z.Score).Take(10)
For Each score As Scores In topTenScores
Dim label As New Label
label.Text = score.Name & " --> " & score.Score
tlpScores.Controls.Add(label)
Next
End Sub
Private Class Scores
Public Property Name As String
Public Property Score As Integer
End Class
答案 1 :(得分:0)
试试这个......
C:
此代码将从* .txt文件中选择前10个结果,并在DataGridView控件中显示结果。我已经添加了' ORDER BY F1 DESC'在SQL语句中按降序对它们进行排序,将DESC更改为ASC以升序。
看到这是课程作业,你应该逐步完成我的代码,弄清楚它做了什么,然后根据你的需要进行修改......也许你得到一个A + ....我将会这样做帮助你一点点......' F1'在SQL语句中是OleDbDataAdapter创建的默认列标识符,因为它无法在文本文件中找到列名....
查看对您提出的编辑问题我可以看到,分数可能位于文本文件的第二列和第一列中的Name中,因此您需要在上面的代码中更改SQL中的Order By ...