here's what my csv file looks like:
1,couchName1,“green”,“suede”
2,couchName2,“blue”,“suede”
3,couchName3,fail,“sued”
...etc.
I need to read this csv and convert each row into a couch object graph. So here is what I tried:
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;
}
I get the error {"Index was outside the bounds of the array."} on the line with the LINQ select statement where I'm trying to parse them into my Couch instances and into a generic list that I want to return them by.
SOLUTION:
Here's how I got it working, solved it myself:
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;
}
我能想到的唯一原因是fileRows中的某些行可能没有预期的四个元素。
figured it out. I needed to split the rows into columns.
See my latest update above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.