从数组中选择随机元素并显示在文本框中

时间:2019-01-26 04:11:14

标签: vb.net

我有一个带有按钮和文本框的表单。我也有一个包含以下内容的文本文件。

Bob:Available:None:0
Jack:Available:None:0
Harry:Available:None:0
Becky:Unavailable:Injured:8
Michael:Available:None:0
Steve:Available:None:0
Annie:Unavailable:Injured:8
Riley:Available:None:0

当用户加载表单时,文本文件的每个值都会存储到数组中。这很好。我想发生的是,当按下按钮时,将从数组中检索值为“ Available”的随机人(姓名)并显示在文本框中。

我到目前为止的代码(将文本文件中的每个项目存储到数组中):

Public Class Form1

    'define profile of person
    Public Structure PersonInfo
        Public name As String
        Public status As String
        Public status_type As String
        Public monthsunavailable As Integer
   End Structure

    'Profile List of persons
    Public Shared personInfos As New List(Of PersonInfo)()   'roster data

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'read all infomations of person from file. lines is profile array
        Dim lines() As String = IO.File.ReadAllLines(filelocation)

        For Each line In lines
            'Parses the line string, make Person Info and add it to Person List

            'split string with ":"
            If line.Trim.Equals("") Then Continue For
            Dim strArr() = line.Split(":")

            'make Person Info
            Dim pi As New PersonInfo()

            pi.name = strArr(0)
            pi.status = strArr(1)
            pi.status_type = strArr(2)
            pi.monthsunavailable = strArr(3)

            'add Person Info to Person List
            personInfos.Add(pi)
        Next

如何从数组中选择一个随机名称并将其显示在文本框中?

1 个答案:

答案 0 :(得分:0)

您可以使用类似这样的东西。尝试阅读文档!

 Private Sub Button1_click (sender As Object, e As EventArgs) Handles Button1.Click
     Dim r As New Random ()
     Textbox1.Text = personinfos(r.Next (0,personinfos.count)).name
 End Sub

更新

仅选择状态为“可用”的名称

 Private Sub Button1_click (sender As Object, e As EventArgs) Handles Button1.Click
     'Instantiate a new random variable
     Dim r As New Random ()
     'This is a LINQ query to select all items from the list where a property of the item
     '(in this case , status) is equal to something. 
     'Try changing Available to something else and see what you get
     Dim qr = From pi in personinfos
                      Where pi.status = "Available"
                      Select pi
      'The following line can be simplified as follows
      'Dim i As Integer = r.Next (0,qr.count)
      'Dim s As String = qr (i).name
      'Textbox1.Text = s
     Textbox1.Text = qr(r.Next (0,qr.count)).name
 End Sub