写一个列表< object>来自CSV文件C# [英] Write to a list<object> from a CSV file C#

查看:67
本文介绍了写一个列表< object>来自CSV文件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找足够的答案,但没有运气。



如标题所示,我正在尝试读取CSV数据到列表。基本上我有一个名为Person的课程:



I was looking for a sufficient answer for quite some time but didn't have any luck.

As the title suggest, I am trying to read CSV data to the list. Basically I have a class called Person:

public string Name { get; set; }
public string Surname { get; set; }
public DateTime DateOfBirth { get; set; }





我试图将它从CSV读到列表。我不确定如何在行方面做到这一点,以便它匹配名称,姓氏,dob



CSV文件看起来像这样: />


姓名姓氏出生日期

Angela Blah 24/01/1990





简而言之,我希望将'Angela'的详细信息插入到Person对象列表中。



我尝试了什么:



我做了几件事:



在我的Person类中创建一个constuctor:





I am trying to read it from the CSV to the List. I'm not sure how to do that in terms of the rows so that it will match the name, surname, dob

The CSV file looks like that:

Name Surname Date Of Birth
Angela Blah 24/01/1990


In short, I want the 'Angela' details to be inserted in the List of Person object.

What I have tried:

I did tried few things:

Create a constuctor in my Person class:

 public Person(string line) 
{ 
        var split = line.Split(',');
        Name = split[0];
        Surname = split[1];
        DateOfBirth = split[2];  
}





然后想要这样使用它:





Then wanted to use it like that:

var people = File.ReadLines("../people.csv").Select(line => new 
             Person(line)).ToList();





当然它是空的因为我是创造一个新人。这是我能想到的最接近的...是答案的正确方向还是完全错误?



But of course it is empty because I am creating a new person. This is closest of what I could think of...is it the right direction for an answer or is it completely wrong?

推荐答案

首先要注意的是您的示例数据与您的代码不匹配:它不包含逗号,因此Split不起作用。

然后,您需要使用DateTime.TryParse或DateTime.TryParseExact将字符串转换为a DateTime。



除此之外,错误的方法名称(应该是File.ReadAllLines)代码应该可以工作 - 但是你应该检查Split操作的结果确保该行确实包含至少三个以逗号分隔的项目。
The first thing to note is that your sample data doesn't match your code: it contains no commas, so the Split won't work.
Then, you need to use DateTime.TryParse or DateTime.TryParseExact to convert the string to a DateTime.

Other than that and the wrong method name (it should be File.ReadAllLines) that code should work - but you should check the results of the Split operation to ensure the line did contain at least three items separated by commas.


这篇关于写一个列表< object>来自CSV文件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆