C# CSV to List: Convert CSV Data into a List of Objects
This article provides a simple yet effective example of converting a CSV file into a List of custom objects in C#. Let's break down the code:
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
string csvFilePath = 'path\to\file.csv';
List<Record> records = new List<Record>();
using (var reader = new StreamReader(csvFilePath))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Record record = new Record();
record.Name = values[0];
record.Age = int.Parse(values[1]);
record.City = values[2];
records.Add(record);
}
}
foreach (var record in records)
{
Console.WriteLine('{0}, {1}, {2}', record.Name, record.Age, record.City);
}
}
}
class Record
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
In this example, we first define a custom class called 'Record' with properties 'Name', 'Age', and 'City'. We then read the CSV file line by line, splitting each line into an array of values using the comma as a delimiter. These values are used to create new 'Record' objects, which are added to the 'records' list.
Finally, we iterate through the list and print the properties of each 'Record' object. This example assumes a consistent format for your CSV data, where each row has Name, Age, and City separated by commas. If your CSV file has a different structure, you'll need to adjust the code accordingly.
This method provides a solid foundation for working with CSV data in C#. By understanding the principles of file reading, parsing, and object creation, you can easily adapt this code to handle various CSV data structures and perform further processing as needed.
原文地址: https://www.cveoy.top/t/topic/oQYy 著作权归作者所有。请勿转载和采集!