C# CSV to Class: Convert CSV Data to Objects
In C#, you can use the following code to convert a CSV file into classes:
First, create a class to store the data from the CSV file. For example, if the CSV file contains name and age columns, you can create the following class:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Then, use the following code to read the CSV file:
List<Person> people = new List<Person>();
using (var reader = new StreamReader('path/to/file.csv'))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Person person = new Person
{
Name = values[0],
Age = int.Parse(values[1])
};
people.Add(person);
}
}
In this code, we first create a List<Person> to store the data from the CSV file. Then, we use a StreamReader to read the CSV file. For each line, we use the Split method to split it into comma-separated values and store these values in a Person object. Finally, we add this Person object to the List<Person>.
Now, we can use the data in the people list. For example, we can use the following code to print the names of all people in the people list:
foreach (Person person in people)
{
Console.WriteLine(person.Name);
}
原文地址: https://www.cveoy.top/t/topic/oQYq 著作权归作者所有。请勿转载和采集!