如何更改此代码以查找所有匹配项

时间:2019-04-16 20:28:21

标签: vb.net

我需要对ID执行子字符串匹配。例如,搜索以“ AB”开头的所有ID,然后返回所有匹配项。 ID格式为AB1234。

    Dim CPosition, HashPostion As Integer
    Dim StudentID, Fileline, IdPart As String
    Dim SPostion As Char
    Dim found As Boolean = False

    FileOpen(1, "StudendRecord.txt", OpenMode.Input)

    Console.Write("Enter ID to find the email: ")
    StudentID = Console.ReadLine()

    Do
        CPosition = 1
        Fileline = LineInput(1)

        Do
            SPostion = Mid(Fileline, CPosition, 1)
            CPosition = CPosition + 1
        Loop Until SPostion = "#"

        HashPostion = Len(Fileline) - (CPosition - 1)
        CPosition = 1
        Do
            SPostion = Mid(Fileline, CPosition, 1)
            IdPart = IdPart + SPostion

            If StudentID = IdPart Then
                Console.WriteLine("the email: " & Right(Fileline, HashPostion))
                found = True
            End If
            CPosition = CPosition + 1
        Loop Until SPostion = "#"
    Loop Until EOF(1)

    If found = False Then
        Console.WriteLine("ID not found.")
    End If
    FileClose(1)

1 个答案:

答案 0 :(得分:0)

要使用此代码,请在文件顶部添加Imports System.IO。该名称空间具有File类。 File.ReadLines返回文本文件中的行和行的数组。

我创建了一个简单的类来将数据保存在文件中。 然后是一个类的类型列表。 然后,我将#字符上的每一行拆分为2个元素的数组。第一个元素将包含ID,第二个元素将包含电子邮件。 创建一个新学生,并将数据传递给构造函数。然后将新学生添加到列表中。

要搜索列表,我使用了Linq。在这种情况下,Linq返回IEnumerable(Of T)T是StudentRecord。

要搜索列表,我使用了Linq。我在生成的IEnumerable上使用了.ToArray,因为我们只需要第一个元素。

Public Class StudentRecord
    Public Property ID As String
    Public Property Email As String
    Public Sub New(id As String, email As String)
        Me.ID = id
        Me.Email = email
    End Sub
End Class

Module Module1
    Private StudentRecords As New List(Of StudentRecord)
    Public Sub Main()
        Dim Records = File.ReadLines("StudentRecord.txt")
        For Each line In Records
            Dim SplitLine = line.Split("#"c)
            Dim stu As New StudentRecord(SplitLine(0), SplitLine(1))
            StudentRecords.Add(stu)
        Next
        Console.Write("Enter ID to find the email: ")
        Dim StudentID = Console.ReadLine()
        Dim students = From stu In StudentRecords
                       Where stu.ID.StartsWith(StudentID)
                       Select stu
        If students.Count > 0 Then
            For Each stu In students
                Console.WriteLine($"Student {stu.ID} email is {stu.Email}")
            Next
        Else
            Console.WriteLine("ID not found.")
        End If
        Console.ReadLine()
    End Sub
End Module