Results 1 to 4 of 4

Thread: [RESOLVED] CSV String split, concatenate & join

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2016
    Posts
    7

    Resolved [RESOLVED] CSV String split, concatenate & join

    Noob question, how can I add ' character or concatenate ' character before and after each item in row before String join?

    Please see below the current code used and outputs.

    Code:
         
    Dim Rows = (From line In IO.File.ReadAllLines(FileTest.csv)
                        Where line.Length > 0
                        Let Items = line.Split(","c)
                        Select Items Skip 1).ToList
    
    For Each row In Rows
     
    ListBox1.Items.Add(String.Join("'", row))
    
    Next
    CSV File:
    fName,dDate
    x1,09/17/2020
    x2,09/16/2020
    x3,09/15/2020

    Current output on ListBox1:
    x1,09/17/2020
    x2,09/16/2020
    x3,09/15/2020

    Needed output on ListBox1:
    'x1','09/17/2020'
    'x2','09/16/2020'
    'x3','09/15/2020'

    Thanks!

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,586

    Re: CSV String split, concatenate & join

    vb.net Code:
    1. ListBox1.Items.Add(String.Join("'", row.Select(Function(s) $"'{s}'")))

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,586

    Re: CSV String split, concatenate & join

    By the way, if you are going to read the file that way, you should be calling ReadLines rather than ReadAllLines. The difference is that ReadAllLines will read the whole file into an array first and you then enumerate that array, while ReadLines actually returns one line at a time for processing, so it is more efficient.

    That said, you probably shouldn't read the file that way. It appears that it will work for the data you have but it wouldn't for all data. Using a TextFieldParser would work for any properly-formatted CSV data.
    Last edited by jmcilhinney; Sep 18th, 2020 at 01:27 AM. Reason: Fixed typo to change "would" to "wouldn't".

  4. #4

    Thread Starter
    New Member
    Join Date
    Jan 2016
    Posts
    7

    Re: CSV String split, concatenate & join

    Thank you sir appreciate the help!

    I will try TextFieldParser as suggested. Thanks a lot!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width