Home > Backend Development > C++ > How to Separate CSV Column Data into Different Arrays in C#?

How to Separate CSV Column Data into Different Arrays in C#?

DDD
Release: 2025-01-26 06:56:09
Original
861 people have browsed it

How to Separate CSV Column Data into Different Arrays in C#?

Categorize and store CSV file data into different arrays

Question:

You are trying to parse a CSV file containing two columns separated by semicolons. For display purposes, the values ​​of each column should be stored separately in an array.

Solution:

Step 1: Create array and initialize StreamReader

Initializes two List arrays: one for each column ("listA" and "listB"). Open the CSV file using StreamReader.

Step 2: Iterate over rows and split values

Use a while loop to iterate over each row in the CSV file. For each row, use the Split() function with a semicolon delimiter to split the values.

Step 3: Store column values ​​into array

Store the first value in the split result into the first list ("listA") and the second value into the second list ("listB").

Sample code:

<code class="language-csharp">using System.IO;

static void Main(string[] args)
{
    using (var reader = new StreamReader(@"C:\test.csv"))
    {
        List<string> listA = new List<string>();
        List<string> listB = new List<string>();
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(';');

            listA.Add(values[0]);
            listB.Add(values[1]);
        }
    }
}</code>
Copy after login

Output:

The values ​​of each column will be stored in the "listA" and "listB" arrays respectively and can be accessed using their index.

The above is the detailed content of How to Separate CSV Column Data into Different Arrays in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template