Home > Backend Development > C++ > How Can I Store CSV File Columns into Separate Arrays in C#?

How Can I Store CSV File Columns into Separate Arrays in C#?

DDD
Release: 2025-01-26 06:51:09
Original
960 people have browsed it

How Can I Store CSV File Columns into Separate Arrays in C#?

Store CSV file values ​​into array

Suppose you have successfully read a CSV file containing two columns (semicolon separated) using StreamReader and Split(). To store each column into a different array, follow these steps:

  1. Create two lists (arrays) to hold the values ​​of each column, such as listA and listB.
  2. Use a while loop to iterate over the CSV file line by line.
  3. For each row, split it into an array using the Split() function, which will decompose the values ​​based on the semicolon separator.
  4. Add the first value (column 1) to listA and the second value (column 2) to listB.

Here is a sample code that demonstrates this process:

<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

With this approach you can effectively store each column of your CSV file into a separate array for further processing or display.

The above is the detailed content of How Can I Store CSV File Columns into Separate 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