从文件中读取文本并比较文本然后存储到相应的列表框

时间:2015-12-03 21:11:18

标签: vb.net

我有一个文本文件,如下所示:

水稻|食品

焦|饮料

我如何检查它是否是食物然后我会将米添加到食物列表中,否则添加到饮品列表?

       For Each line In File.ReadAllLines(path)

            Dim temp() As String = line.Split(New Char() {"|"})
            '  Dim tempFood As String() = temp
            '   For Each temp1 In temp

            ' if food then add rice to food list
            ' else add coke to drink list

            If temp.Length = 2 Then

                Dim kind = temp(1).Trim().ToLower()

                If kind = "food" Then
                    lstFood.Items.Add(temp(0).trim())
                ElseIf kind = "beverage" Then
                    lstBeverage.Items.Add(temp(0).trim())
                End If

            End If


            'Next
        Next

1 个答案:

答案 0 :(得分:0)

分割线后,你应检查数组中是否有两个元素,如果检查结果是肯定的,那么第二个元素包含字符串“food”或“drink”。只是一个if来选择正确的字符串列表

Dim foodList  = new List(Of String)()
Dim drinkList = new List(Of String)()

For Each line In File.ReadAllLines(path)
    Dim temp() As String = line.Split(New Char() {"|"})
    If temp.Length = 2 Then
       Dim kind = temp(1).Trim().ToLower()
       if kind = "food" Then
          foodList.Add(temp(0).Trim())
       else if kind = "drink" Then
          drinkList.Add(temp(0).Trim())
       else

          MessageBox.Show("Unexpected kind: " & kind)

       End if
    End If
Next