CSV 到对象模型映射
我有一个 CSV 文件,我想将其读入列表中。这是一个示例文件:
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 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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于问题中显示的特定数据...
如果您已经为数据声明了类型,那么您可以使用它而不是匿名类型。
请注意,此代码根本不健壮。。它无法正确处理包含逗号/换行符等的值、带引号的字符串值或 CSV 文件中常见的任何其他深奥内容。
For the specific data shown in your question...
If you already have a type declared for your data then you can use that rather than the anonymous type.
Note that this code isn't robust at all. It won't correctly handle values containing commas/newlines etc, quoted string values, or any of the other esoteric stuff that is often found in CSV files.
您可以使用像这样的简单代码,它会忽略标题并且不能使用引号,但可能足以满足您的需求。
或者您可以像其他人建议的那样使用图书馆。
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.
Or you can use a library, like others suggested.
有一个代码项目:
http://www.codeproject.com/KB/linq/ LINQtoCSV.aspx
但是,您可能需要查看此处:
Linq 和 Streamreader 获取行< /a>
There's a codeproject for that:
http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
However, you may want to look here:
Linq and streamreader getting lines
我编写了一个简单的库,允许开发人员在 CSV 文件上使用 LINQ。这是我关于它的博客文章:http://procbits。 com/2010/10/11/using-linq-with-csv-files/
在你的情况下,你必须将标题字符串更改为如下所示:
然后你可以像这样解析文件
:然后可以像这样使用 LINQ:
希望对您有帮助或有用。
I wrote a simple library to allow developers to use LINQ on CSV files. Here is my blog post about it: http://procbits.com/2010/10/11/using-linq-with-csv-files/
In your case, you would have to change your header string to look like this:
And then you could parse the file like this:
You could then use LINQ like this:
Hope that helps or works for you.
它不使用 LINQ,但 CsvHelper 是一种将 CSV 解析为 .NET 对象的简单方法:
It doesn't use LINQ but CsvHelper is a simple method to implement CSV parsing to a .NET object:
使用Cinchoo ETL库,可以将CSV文件解析为对象
定义类型匹配的CSV文件结构如下
加载 CSV 文件
With Cinchoo ETL library, can parse CSV file into objects
Define type matching CSV file structure as below
Load the CSV file