簡體   English   中英

VB.NET使用拆分功能對數組進行排序

[英]VB.NET Sort array using split function

我創建了這個程序,該程序將組裝一個排行榜數組,該數組將存儲游戲中的分數以及分數旁邊的用戶名。 每次玩游戲時,此排行榜都會不斷更新。 這些分數將附加到文本文件中,並將文本文件的內容輸入到排行榜陣列中。 我想對這個數組進行排序,以使分數遞減,當然,相應分數旁邊有玩家名稱。 該數組如下所示:

| User1,9.0,2,0 | User2,8.0,0,1 | User3,8.5,0,1

因此,此數組的格式如下:

|用戶名1,總分,獲勝,失敗| Username2,totalscore,贏,輸...

我將如何對該數組進行排序,以使得分最高的用戶首先出現在數組中並顯示出來? 我聽說合並排序最簡單,但這是真的嗎? 感謝您的幫助!

您可以用測斜儀"|"分割 然后像這樣利用OrderByDescending

Dim resultSet As String() = myString.Split("|"c) _
        .Where(Function(s) Not String.IsNullOrWhitespace(s)) _
        .OrderByDescending(
            Function(s) 
                Dim str as String = s.Substring(s.IndexOf(" ") + 1)
                Dim count As Integer = str.IndexOf(",")             
                Return Double.Parse(str.Substring(0, count))
            End Function) _
        .ToArray()

或者如果您希望將元素放入List(Of String)則只需更改:

Dim resultSet As String()

至:

Dim resultSet As List(Of String)

然后在上面的管道中將ToArray()調用更改為ToList()

上面代碼的最終結果是一個String數組:

User1, 9.0, 2, 0
User3, 8.5, 0, 1
User2, 8.0, 0, 1

不要忘記使用以下導入:

Imports System.Linq 
Imports System.Collections.Generic

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM