【问题标题】:Read CSV to a list of classes读取 CSV 到类列表
【发布时间】:2017-10-16 21:06:41
【问题描述】:

我有一个包含用逗号分隔的信息的 CSV 歌曲文件,我想将它们转换为类列表(参见类下方)。

对不起,如果我解释得不好

例如:

Waiting For Love,Avicii,Tanecni Liga 171,Dance & House,Avicii,,1,2015,,,,

问题是我有一些带有引号的歌曲,而引号内有一个逗号 例如:

Hey Brother,Avicii,TRUE,House,Avicii,,3 of 12,2013,,,"Tim Bergling, Ash Pournouri, Vincent Pontare & Salem Al Fakir",

问题是我想要那个 - “Tim Bergling, Ash Pournouri, Vincent Pontare & Salem Al Fakir” 将是一个字符串,但如果我用一个类似逗号的解决方案拆分,我在这里找到的解决方案会在中间切开我不想写的字符串

如果我在这一行使用Split(',');,它会这样做:

Hey Brother
Avicii
TRUE
House
Avicii
//empty string because there is ',,'
3 of 12
2013
//empty string because there is ',,'
//empty string because there is ',,'
"Tim Bergling
 Ash Pournouri
 Vincent Pontare & Salem Al Fakir"
//empty string because there is ',,'

相反,我想要这个:

Hey Brother
Avicii
TRUE
House
Avicii
//empty string because there is ',,'
3 of 12
2013
//empty string because there is ',,'
//empty string because there is ',,'
Tim Bergling, Ash Pournouri, Vincent Pontare & Salem Al Fakir
//empty string because there is ',,'

这是我的歌曲课:

    `public class song
    {
        private string name; // Name of the song
        private string artist; // Name of the artist
        private string album; // The name of the album
        private string genre; // The Genre of the song
        private string album_Artist; // Artist name of the album
        private string release_Date; // The release date of the song
        private string track; // The number of the track of the number of the count of the tracks - a.k 4 of 12
        private string year; // The year that the song came
        private string comments; // The comments for the song
        private string description; // The description for the song
        private string composer; // The composer of the song;
        private string grouping; // The grouping of the song
    }

我对每个字符串都有 Get 和 Sets 操作(我剪掉了它们,因为它太长了)

【问题讨论】:

标签: c# list class csv


【解决方案1】:

在不使用任何特殊库的情况下,您只需在 C# 代码中引用 Microsoft.VisualBasic 并按照以下说明使用 TextFieldParser

(复制自https://stackoverflow.com/a/3508572/1658434

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    while (!parser.EndOfData) 
    {
        //Processing row
        string[] fields = parser.ReadFields();
        foreach (string field in fields) 
        {
            //TODO: Process field
        }
    }
}

我已经使用您的示例对其进行了测试,它可以按您的需要工作。

【讨论】:

  • 非常感谢!,我稍后会检查这个,但是这是如何将“”中的内容定义为一个字符串?
  • 嗯,TextFieldParser,顾名思义,就是一个解析器。所以我相信它考虑了分隔文件的规则和格式。这允许一个字段用双引号引起来,因此可以这样识别它。
猜你喜欢
  • 2022-01-05
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 2023-01-25
  • 2019-06-17
  • 1970-01-01
相关资源
最近更新 更多