本文介绍了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?

推荐答案

您可以使用这样的简单代码,它会忽略标题并且不使用引号,但可能足以满足您的需求.

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 到对象模型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 00:38