将CSV解析为模型

时间:2016-10-05 06:50:37

标签: c# .net csv ienumerable

我尝试将CSV解析为模型,但我的IEnumerable始终为空。这段代码有问题吗?

private IEnumerable<CandidatesDTO> FileToDto(byte[] file)
{
    System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
    IEnumerable<CandidatesDTO> query = null;
    string[] separators = { ",", ".", "!", "?", ";", ":", " " };
    try
    {
        var str = enc.GetString(file);
        query = from line in str
                let data = str.Split(separators, StringSplitOptions.RemoveEmptyEntries)
                select new CandidatesDTO
                {
                    Id = Int32.Parse(data[0]),
                    Name = data[1],
                    DOB = DateTime.Parse(data[2], CultureInfo.InvariantCulture),
                    Phone = data[3],
                    Email = data[4]
                };
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    return query;
}

更新即可。我发现有异常 - &#34;输入字符串的格式不正确&#34;。看起来像是一些不正确的类型与字符串一起传递,这导致了FormatException。

1 个答案:

答案 0 :(得分:0)

通过查看代码,我认为linq将str视为IEnumerable<char>。您可能需要执行str.Split("\r\n")或行分隔符,以便获得每一行。

private IEnumerable<CandidatesDTO> FileToDto(byte[] file)
{
    System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
    IEnumerable<CandidatesDTO> query = null;
    string[] separators = { ",", ".", "!", "?", ";", ":", " " };
    try
    {
        var str = enc.GetString(file);
        query = from line in str.Split(new [] {"\n\r"}, StringSplitOptions.RemoveEmptyEntries)
                let data = line.Split(separators, StringSplitOptions.RemoveEmptyEntries)
                select new CandidatesDTO
                {
                    Id = Int32.Parse(data[0]),
                    Name = data[1],
                    DOB = DateTime.Parse(data[2], CultureInfo.InvariantCulture),
                    Phone = data[3],
                    Email = data[4]
                };
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    return query;
}