将CSV读取到类列表

时间:2017-05-17 11:58:35

标签: c# list class csv

我有一个歌曲的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和Set(我剪切它们因为它太长了)

1 个答案:

答案 0 :(得分: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
        }
    }
}

我已经使用您的示例测试了它,它可以根据您的需要运行。