这是我的 csv 文件的样子:
1,couchName1,“green”,“suede”
2,couchName2,“blue”,“suede”
3,couchName3,fail,“sued”
...etc.
我需要阅读此 csv 并将每一行转换为沙发对象图。所以这是我尝试过的:
public static IEnumerable<string[]> ReadCsvFile(string filePath)
{
IEnumerable<string[]> file = File.ReadLines(filePath).Select(a => a.Split(';'));
return file;
}
public static List<Couch> GetCouches(string csvFilePath)
{
IEnumerable<string[]> fileRows = FileUtilities.ReadCsvFile(csvFilePath);
if (fileRows == null) return new List<Couch>();
int couchId;
List<Couch> couches = fileRows.Select(row => new Couch
{
CouchId = int.TryParse(row[0], out couchId) ? couchId : 0,
Name= row[1],
Color= row[2],
Fabric= row[3]
}).ToList();
return couches;
}
我得到错误 {"Index was outside the bounds of the array."} 在 LINQ select 语句的行上,我试图将它们解析到我的 Couch 实例和我想要返回它们的通用列表中。
解决方案:
这是我如何让它工作的,我自己解决了它:
public static List<Couch> GetCouches(string csvFilePath)
{
IEnumerable<string[]> fileRows = FileUtilities.ReadCsvFile(csvFilePath);
List<Couch> couches = new List<Couch>(); // ADDED THIS
if (fileRows == null) return new List<Couch>();
int couchId;
// NEW LOGIC, SPLIT OUT EACH ROW'S COLUMNS AND THEN MAKE THE OBJECT GRAPH
foreach(string[] row in fileRows)
{
string[] rowColumnValues = row[0].Split(',').ToArray();
couches.Add(new Couch
{
CouchId = int.TryParse(rowColumnValues[0], out couchId) ? couchId : 0,
Name= rowColumnValues[1],
Color= rowColumnValues[2],
Fabric= rowColumnValues[3]
}
return couches;
}