locked
Getting a certain value from a list RRS feed

  • Question

  • Hello,

    I need to get the first value out of a list I'm reading from an external text file.

    The file is displayed like:

    Alright , Magic Gang

    etc...

    I need to just read the value before the comma.

    Any help would be appreciated.

    Wednesday, April 10, 2019 12:23 PM

All replies

  • Hi

    Here is one way:

            ' file may have multiplr lines
            ' read all lines from it
            Dim allitems As List(Of String) = IO.File.ReadLines(path).ToList
    
            ' take first line and split at ","
            Dim items As String() = allitems(0).Split(","c)
    
            ' put desired item into variable
            Dim wanteditem As String = items(0)


    Regards Les, Livingston, Scotland

    • Proposed as answer by Alex-KSGZ Friday, April 12, 2019 8:55 AM
    Wednesday, April 10, 2019 2:12 PM
  • Hello,

    Here is a simple example which reads a delimited text file and returns only the first column/field.

    First create states.csv and place it in the same folder as this project executable. Populate with this data.

    Add a ComboBox to the form named stateNamesComboBox, use the code below.

    Imports System.IO
    
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) _
            Handles MyBase.Load
    
            Dim ops = New FileOperations
            stateNamesComboBox.DataSource = ops.GetStateNames
    
            Dim oregonPosition = stateNamesComboBox.FindStringExact("Oregon")
            If oregonPosition > -1 Then
                stateNamesComboBox.SelectedIndex = oregonPosition
            End If
    
        End Sub
    End Class
    Public Class FileOperations
        Public Function GetStateNames() As List(Of String)
            Dim fileName = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory, "States.csv")
    
            '
            ' Assumes there are at least two columns per row in the file
            ' delimited by a comma. All blank lines are skipped
            '
            Dim dataList = (
                From line In File.ReadAllLines(fileName)
                Where line.Length > 0
                Let items = line.Split(","c)
                Select items(0)).
                ToList
    
            Return dataList
    
        End Function
    End Class
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, April 10, 2019 2:32 PM