以下是将 CSV 文件转换为 List 类的 C# 代码示例:

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

class Program
{
    static void Main(string[] args)
    {
        string file = "data.csv";

        List<Person> people = new List<Person>();

        using (StreamReader reader = new StreamReader(file))
        {
            // 跳过标题行
            reader.ReadLine();

            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                string[] fields = line.Split(',');

                Person person = new Person();

                person.FirstName = fields[0];
                person.LastName = fields[1];
                person.Age = int.Parse(fields[2]);

                people.Add(person);
            }
        }

        // 对人员列表执行其他操作...
    }
}

class Person
{
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int Age { get; set; } 
}

在此示例中,我们假设我们有一个名为“data.csv”的 CSV 文件,其中包含以下内容:

'First Name','Last Name','Age'
'John','Doe',30
'Jane','Smith',25

我们使用 StreamReader 打开文件并按行读取它。我们跳过第一行(标题行),然后对每个行执行以下操作:

  1. 使用 Split 方法将行拆分为字段数组。
  2. 创建一个新的 Person 对象,并将数组中的字段分配给 Person 对象的属性。
  3. 将 Person 对象添加到 List 类中。

最后,我们可以使用 List 类中的人员数据执行其他操作。


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

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