C# CSV File Column Separation into Arrays: A Streamlined Approach
This guide demonstrates an efficient method for parsing a CSV file and distributing its columns into individual arrays using C#.
Procedure:
StreamReader Initialization: Begin by creating a StreamReader
object, providing the path to your CSV file as an argument.
Array Initialization: Declare two empty lists (List<string>
)—listA
and listB
—to hold the data from each column. This dynamic approach allows for handling CSV files with varying numbers of rows.
Line-by-Line Processing: Use a while
loop to iterate through each line of the CSV file until the end is reached (reader.EndOfStream
).
Data Extraction: Inside the loop, ReadLine()
retrieves a single line. The Split(';')
method then divides the line into an array of strings based on the semicolon delimiter (adjust as needed for your CSV's delimiter).
Array Population: Assign the extracted values to their respective lists. listA.Add(values[0])
adds the first element (column 1) to listA
, and listB.Add(values[1])
adds the second element (column 2) to listB
.
Loop Continuation: The loop continues until all lines are processed.
Code Example:
<code class="language-csharp">using System.IO; using System.Collections.Generic; public class CsvParser { public static void Main(string[] args) { string filePath = @"C:\test.csv"; // Replace with your file path using (var reader = new StreamReader(filePath)) { List<string> listA = new List<string>(); List<string> listB = new List<string>(); while (!reader.EndOfStream) { string line = reader.ReadLine(); string[] values = line.Split(';'); if (values.Length >= 2) //Error handling for lines with less than 2 columns. { listA.Add(values[0]); listB.Add(values[1]); } else { Console.WriteLine($"Skipping line: {line} (Insufficient columns)"); } } //Further processing or output of listA and listB can be added here. Console.WriteLine("List A: " + string.Join(", ", listA)); Console.WriteLine("List B: " + string.Join(", ", listB)); } } }</code>
This enhanced example includes error handling for lines with fewer than two columns, preventing potential exceptions. Remember to replace "C:test.csv"
with the actual path to your CSV file. This improved method provides a robust and efficient solution for separating CSV columns into arrays.
The above is the detailed content of How Can I Efficiently Separate CSV File Columns into Arrays in C#?. For more information, please follow other related articles on the PHP Chinese website!