本文介绍了CSV对象模型映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我要读入列表的CSV文件。这里有一个例子文件:
I have a CSV file that I want to read into a List. Here's an example file:
Plant,Material,"Density, Lb/ft3",Storage Location
FRED,10000477,64.3008,3300
FRED,10000479,62.612,3275
FRED,10000517,90,3550
FRED,10000517,72,3550
FRED,10000532,90,3550
FRED,10000532,72,3550
FRED,10000550,97,3050
我知道我可以在CSV文件中手动读取和使用普通的StreamReader生成列表,但我不知道是否有更好的方法,可能使用LINQ?
I know I can manually read in the CSV file and build the list using a normal StreamReader, but I was wondering if there was a better way, perhaps using LINQ?
推荐答案
您可以使用一个简单的code这样的,它忽略了头,不带引号工作,但可能会为您的需求是足够的。
You can use a simple code like this, which ignores the header and doesn't work with quotes, but may be sufficient for your needs.
from line in File.ReadAllLines(fileName).Skip(1)
let columns = line.Split(',')
select new
{
Plant = columns[0],
Material = int.Parse(columns[1]),
Density = float.Parse(columns[2]),
StorageLocation = int.Parse(columns[3])
}
或者你也可以使用一个图书馆,像其他人一样建议。
Or you can use a library, like others suggested.
这篇关于CSV对象模型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!