C# CSV 文件转 List<Person> 实体类教程
假设我们有一个 CSV 文件,其中包含以下内容:
Id,Name,Age
1,John,25
2,Jane,30
3,Bob,40
我们可以创建一个实体类来表示每一行数据:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
然后,我们可以编写以下代码将 CSV 文件转换为 List
using System;
using System.Collections.Generic;
using System.IO;
public class Program
{
public static void Main()
{
List<Person> people = new List<Person>();
using (var reader = new StreamReader('people.csv'))
{
// Skip the header row
reader.ReadLine();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
var person = new Person
{
Id = int.Parse(values[0]),
Name = values[1],
Age = int.Parse(values[2])
};
people.Add(person);
}
}
// Do something with the list of people
foreach (var person in people)
{
Console.WriteLine('{0}: {1} ({2})', person.Id, person.Name, person.Age);
}
}
}
在这个示例中,我们使用了 StreamReader 来读取 CSV 文件,并使用 Split 方法将每一行数据拆分为一个字符串数组。然后,我们使用这些值来创建一个新的 Person 实例,并将其添加到 List
原文地址: https://www.cveoy.top/t/topic/oF6r 著作权归作者所有。请勿转载和采集!