CSV 到对象模型映射

发布于 2024-09-14 10:32:04 字数 352 浏览 2 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

作业与我同在 2024-09-21 10:32:04

对于问题中显示的特定数据...

var yourData = File.ReadAllLines("yourFile.csv")
                   .Skip(1)
                   .Select(x => x.Split(','))
                   .Select(x => new
                                {
                                    Plant = x[0],
                                    Material = x[1],
                                    Density = double.Parse(x[2]),
                                    StorageLocation = int.Parse(x[3])
                                });

如果您已经为数据声明了类型,那么您可以使用它而不是匿名类型。

请注意,此代码根本不健壮。。它无法正确处理包含逗号/换行符等的值、带引号的字符串值或 CSV 文件中常见的任何其他深奥内容。

For the specific data shown in your question...

var yourData = File.ReadAllLines("yourFile.csv")
                   .Skip(1)
                   .Select(x => x.Split(','))
                   .Select(x => new
                                {
                                    Plant = x[0],
                                    Material = x[1],
                                    Density = double.Parse(x[2]),
                                    StorageLocation = int.Parse(x[3])
                                });

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.

霓裳挽歌倾城醉 2024-09-21 10:32:04

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

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])
}

或者您可以像其他人建议的那样使用图书馆。

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.

夜还是长夜 2024-09-21 10:32:04

有一个代码项目:

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

无敌元气妹 2024-09-21 10:32:04

我编写了一个简单的库,允许开发人员在 CSV 文件上使用 LINQ。这是我关于它的博客文章:http://procbits。 com/2010/10/11/using-linq-with-csv-files/

在你的情况下,你必须将标题字符串更改为如下所示:

Plant,Material,DensityLbft3,StorageLocation

然后你可以像这样解析文件

var linqCSV = new CsvToXml("csvfile", true);
linqCsv.TextQualifier = null;

linqCsv.ColumnTypes.Add("Plant", typeof(string));
linqCsv.ColumnTypes.Add("Material", typeof(int));
linqCsv.ColumnTypes.Add("DensityLbft3", typeof(double));
linqCsv.ColumnTypes.Add("StorageLocation", typeof(int));

linqCsv.Convert();

:然后可以像这样使用 LINQ:

var items = from item in linqCsv.DynamicRecords
            where item.Plant == "Fred" && item.DensityLbft3 >= 62.6
            orderby item.StorageLocation
            select item;

希望对您有帮助或有用。

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:

Plant,Material,DensityLbft3,StorageLocation

And then you could parse the file like this:

var linqCSV = new CsvToXml("csvfile", true);
linqCsv.TextQualifier = null;

linqCsv.ColumnTypes.Add("Plant", typeof(string));
linqCsv.ColumnTypes.Add("Material", typeof(int));
linqCsv.ColumnTypes.Add("DensityLbft3", typeof(double));
linqCsv.ColumnTypes.Add("StorageLocation", typeof(int));

linqCsv.Convert();

You could then use LINQ like this:

var items = from item in linqCsv.DynamicRecords
            where item.Plant == "Fred" && item.DensityLbft3 >= 62.6
            orderby item.StorageLocation
            select item;

Hope that helps or works for you.

_蜘蛛 2024-09-21 10:32:04

它不使用 LINQ,但 CsvHelper 是一种将 CSV 解析为 .NET 对象的简单方法:

using (TextReader txt = new StreamReader(filename))
{
    using (var csv = new CsvReader(txt))
    {
        var records = csv.GetRecords<PlantMaterial>();
        return records.ToList();
    }
}

It doesn't use LINQ but CsvHelper is a simple method to implement CSV parsing to a .NET object:

using (TextReader txt = new StreamReader(filename))
{
    using (var csv = new CsvReader(txt))
    {
        var records = csv.GetRecords<PlantMaterial>();
        return records.ToList();
    }
}
笑脸一如从前 2024-09-21 10:32:04

使用Cinchoo ETL库,可以将CSV文件解析为对象

定义类型匹配的CSV文件结构如下

public class PlantType
{
    public string Plant { get; set; }
    public int Material { get; set; }
    public double Density { get; set; }
    public int StorageLocation { get; set; }
}

加载 CSV 文件

static void LoadCSV()
{
    using (var p = new ChoCSVReader<PlantType>("*** YOUR CSV FILE PATH ***")
        .WithFirstLineHeader(true)
        )
    {
        foreach (var rec in p)
        {
            Console.WriteLine(rec.Dump());
        }
    }
}

With Cinchoo ETL library, can parse CSV file into objects

Define type matching CSV file structure as below

public class PlantType
{
    public string Plant { get; set; }
    public int Material { get; set; }
    public double Density { get; set; }
    public int StorageLocation { get; set; }
}

Load the CSV file

static void LoadCSV()
{
    using (var p = new ChoCSVReader<PlantType>("*** YOUR CSV FILE PATH ***")
        .WithFirstLineHeader(true)
        )
    {
        foreach (var rec in p)
        {
            Console.WriteLine(rec.Dump());
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文