我尝试将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。
答案 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;
}