This C# code efficiently separates CSV columns into individual arrays. Let's refine it for clarity and robustness.
Improved C# Code for CSV Column Separation:
This version handles potential errors, such as missing values or incorrect delimiters, and allows for a variable number of columns:
<code class="language-csharp">using System; using System.Collections.Generic; using System.IO; using System.Linq; public class CsvSplitter { public static List<List<string>> SeparateCsvColumns(string filePath, char delimiter = ';') { List<List<string>> columns = new List<List<string>>(); try { using (var reader = new StreamReader(filePath)) { string line; bool firstLine = true; while ((line = reader.ReadLine()) != null) { string[] values = line.Split(delimiter); if (firstLine) { // Initialize lists for each column on the first line for (int i = 0; i < values.Length; i++) { columns.Add(new List<string>()); } firstLine = false; } // Add values to corresponding columns. Handles lines with fewer values than the header. for (int i = 0; i < Math.Min(values.Length, columns.Count); i++) { columns[i].Add(values[i].Trim()); //Trim whitespace } } } } catch (FileNotFoundException) { Console.WriteLine($"Error: File not found at {filePath}"); return null; // Or throw a more specific exception } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); return null; // Or throw a more specific exception } return columns; } public static void Main(string[] args) { string filePath = @"C:\test.csv"; //Replace with your file path List<List<string>> separatedColumns = SeparateCsvColumns(filePath); if (separatedColumns != null) { for (int i = 0; i < separatedColumns.Count; i++) { Console.WriteLine($"Column {i + 1}:"); foreach (string value in separatedColumns[i]) { Console.WriteLine(value); } Console.WriteLine(); } } } }</code>
This improved code:
try-catch
blocks to handle FileNotFoundException
and other potential exceptions.Trim()
to remove leading/trailing whitespace from each value.Remember to replace "C:test.csv"
with the actual path to your CSV file. This robust solution provides a more reliable and versatile approach to processing CSV data in C#.
The above is the detailed content of How Can I Separate CSV Columns into Individual Arrays in C#?. For more information, please follow other related articles on the PHP Chinese website!