This guide demonstrates how to convert data from a CSV file into C# data classes using the CsvHelper library. It provides a step-by-step tutorial with code examples to efficiently handle CSV data in your C# applications.

Scenario:

Imagine you have a CSV file containing data like this:

Name, Age, Gender
John, 25, Male
Jane, 30, Female

You can define a C# data class to represent this data:

public class Person
{
    public string Name { get; set; } 
    public int Age { get; set; } 
    public string Gender { get; set; } 
}

Using CsvHelper:

The CsvHelper library simplifies CSV parsing in C#. Here's how you can read the CSV and transform each row into a Person object:

using CsvHelper;
using System.Collections.Generic;
using System.IO;

public class CsvReader
{
    public List<Person> ReadCsv(string path)
    {
        using (var reader = new StreamReader(path))
        using (var csv = new CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture))
        {
            var records = csv.GetRecords<Person>();
            return records.ToList();
        }
    }
}

This method reads the CSV file, maps each row to a Person object, and returns a list of those objects.

Usage Example:

var reader = new CsvReader();
var people = reader.ReadCsv("data.csv");
foreach (var person in people)
{
    Console.WriteLine('Name: ' + person.Name + ', Age: ' + person.Age + ', Gender: ' + person.Gender);
}

This code reads the CSV data, creates Person objects, and prints the information for each person to the console, resulting in the following output:

Name: John, Age: 25, Gender: Male
Name: Jane, Age: 30, Gender: Female

Benefits of Using CsvHelper:

  • Simplified CSV Parsing: Easily read and write CSV data without manual string manipulation.
  • Mapping to Data Classes: Effortlessly convert CSV data into custom C# objects.
  • Performance Optimization: Handles large CSV files efficiently.
  • Customizable Options: Offers flexibility for handling various CSV formats and data types.

To get started with CsvHelper, you can install it from NuGet using the following command:

Install-Package CsvHelper

This guide provides a basic introduction to using CsvHelper. Explore its documentation for more advanced features and customization options to effectively manage CSV data in your C# projects.


原文地址: https://www.cveoy.top/t/topic/oQ0b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录