How to declare text with a line

后端 未结 4 1732
日久生厌
日久生厌 2021-01-28 23:03

I\'m new to programming and decided to take VB.net up as my first language, I\'m quite new and I\'m currently trying to write a sorting program. I\'m trying to load in a file, s

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-28 23:08

    Using a regular expression to check for a match and extract the score values would be one option. Using File.ReadLines (or File.ReadAllLines pre .NET 4.0) will simplify the IO. You can also use LINQ to query for the matching lines and sort them:

    Dim sortedScores =
        From line in File.ReadLines("S:\class" & CName & ".rtf")
        Let match = Regex.Match(line, "Score: (\d+)")
        Where match.Success
        Order By CInt(match.Groups(1).Value) Descending
        Select line
    For Each line In sortedScores
        Console.WriteLine(line)
    Next
    

    You can remove the Descending is you want lowest to highest.

    If you want to extract the score values, you could modify the query slightly:

    Dim justTheScores =
        From line in File.ReadLines("S:\class" & CName & ".rtf")
        Let match = Regex.Match(line, "Score: (\d+)")
        Where match.Success
        Select CInt(match.Groups(1).Value)
    

    justTheScores will be an IEnumerable(Of Integer) containing just the scores.

    More useful may be to extract the name and score:

    Dim results =
        From line in File.ReadLines("S:\class" & CName & ".rtf")
        Let match = Regex.Match(line, "Name: (.*) \| Score: (\d+)")
        Where match.Success
        Select Name = match.Groups(1).Value, Score = CInt(match.Groups(2).Value)
    

    This will give you an IEnumerable of anonymous types with Name and Score properties.

提交回复
热议问题