用逗号分隔符VB存储从txt文件的文本,以二维数组逗号、数组、文本、文件

由网友(再拽、有個叼用)分享简介:我搜索一个答案,而是奋力我的发现适应了我的code /文本文件。I've searched for an answer, but struggling to adapt my findings into my code/text file.我有这个文本文件; 20,本10,戴夫7,鲍勃·I have thi...

我搜索一个答案,而是奋力我的发现适应了我的code /文本文件。

I've searched for an answer, but struggling to adapt my findings into my code/text file.

我有这个文本文件; 20,本 10,戴夫 7,鲍勃·

I have this text file; 20,Ben 10,Dave 7,Bob

分数和名称。

我想拉从文本文件中的数据到一个二维数组,例如:

I want pull the data from the text file into a 2D array, for example:

阵列(0,0) 阵列(1,0) 阵列(0,1) 阵列(1,1) 阵列(0,2) 阵列(1,2)

array(0, 0) array(1, 0) array(0, 1) array(1, 1) array(0, 2) array(1, 2)

这将转化;

阵列(20) 阵列(本) 阵列(10) 阵列(戴维) 阵列(7) 阵列(BOB)

array(20) array(Ben) array(10) array(Dave) array(7) array(Bob)

在此先感谢

推荐答案

正如我的意见,我会用一个类此。

As mentioned in my comment,i would use a class for this.

例如播放具有两个属性:名称作为字符串分数作为的Int32 。然后,您可以创建一个列表(最佳球员)代替。这比用指数摆弄周围更可读,可重用性和可维护性,也更不容易出错。

For example Player with two properties: Name As String and Score As Int32. Then you can create a List(Of Player) instead. That's much more readable, reusable and maintainable and also less error-prone than fiddling around with indices.

Public Class Player
    Public Property Name As String
    Public Property Score As Int32
End Class

下面是初始化列表(最佳球员)可读LINQ查询从一个文本文件中的行:

Here is a readable LINQ query that initializes a List(Of Player) from lines in a text-file:

Dim allPlayers = From line In System.IO.File.ReadLines("path")
                 Let Columns = line.Split(","c)
                 Where Columns.Length = 2
                 Let Score = Int32.Parse(Columns(0).Trim())
                 Let Name = Columns(1).Trim()
                 Select New Player With {.Score = Score, .Name = Name}
Dim playerList As List(Of Player) = allPlayers.ToList()

如果你需要一个阵列中使用的ToArray 而不是了ToList

If you need an array use ToArray instead of ToList.

您可以通过索引访问ALIST像一个数组(列表(0))或通过LINQ方法:

You can access alist like an array via indexer(list(0)) or via LINQ methods:

Dim firstPlayer As Player = playerList.FirstOrDefault()  ' is Nothing if there are no players '
Console.WriteLine("Name of the player: " & firstPlayer.Name)
Console.WriteLine("His score is: " & firstPlayer.Score)

或在一个循环:

or in a loop:

For Each player In playerList
    Console.WriteLine("Player {0} has scored {} points.", player.Name, player.Score)
Next

顺便说一句,LINQ是非常有用的,让您的code可读,该机还采用循环引擎盖下。所以,你可以简单地使用 OrderByDescendending 订购你的球员按分数输出前3名得分最高的:

By the way, LINQ is useful to keep your code readable, under the hood it also uses loops. So you could simply use OrderByDescendending to order your players by score and output the top 3 with the highest score:

Dim best3Players = From player In playerList
                   Order By Player.Score Descending
                   Take 3
                   Select String.Format("{0}({1})", player.Name, player.Score)
Dim output = String.Join(", ", best3Players)
Windows.Forms.MessageBox.Show(output) ' since you have mentioned messagebox '
阅读全文

相关推荐

最新文章