如何在列表中拆分行?

时间:2019-06-14 02:47:04

标签: c#

我是C#的新手,需要进行家庭作业,我需要使用openfiledialog读取CSV文件,然后将它们添加到列表中,但是我不知道如何使用','分隔行。

我已经尝试过在行后添加.split,并且我也已经尝试过添加值,但是它不允许这样做。

openFileDialog1.ShowDialog();
var fileName = openFileDialog.FileName;
using(StreamReader sr = new StreamReader(fileName))
{
    List<Employee_Record> Employees = new List<Employee_Record>();
    var lines = sr.ReadLine();
    var value = lines.Split(',');

    Employees.Add(new Employee_Record() { Name = lines, Address = lines, Age = lines, GrossMonthlyPay = lines, DepartmentID = lines, DeveloperType = lines, TaxType = lines });
    dataGridView1.DataSource = Employees;
}

2 个答案:

答案 0 :(得分:2)

您必须访问值数组。不是线。而且您需要一个循环才能逐行读取。

using(StreamReader sr = new StreamReader(fileName))
{
    List<Employee_Record> Employees = new List<Employee_Record>();

    while((line = sr.ReadLine()) != null)  
    {  
        var value = line.Split(','); 

        //// some positions can be empty. So handle that
        Employees.Add(new Employee_Record() 
          {   
              Name = value[0] , 
              Address = value[1] , 
              Age = value[2] , 
              GrossMonthlyPay = value[3] , 
              DepartmentID = value[4] , 
              DeveloperType = value[5] , 
              TaxType = value[6]  
          });
    }  

    dataGridView1.DataSource = Employees;
}

答案 1 :(得分:1)

假设您有这样的CSV文件:

2A,18,Stephen Hawk,math,96

我只是将regEx与C#一起使用来解析它。

openFileDialog1.ShowDialog();
var fileName = openFileDialog.FileName;

using(StreamReader sr = new StreamReader(fileName))
{
    List<Employee_Record> Employees = new List<Employee_Record>();
    var lines = sr.ReadLine();
    Regex re = new Regex(@"\W?");
    MatchCollection mc = re.Matches(lines);
    int mIdx=0;
    foreach (Match m in mc){
        Console.writeline(m.Value);
    }
// Do your logic here as you wish
}

//预期输出 2A 18岁 史蒂芬·霍克 数学 96