I'm reading a CSV file and am basically trying to use the headers to determine the ordinal position of the values in the file, though the last part is giving me some trouble. The following is what I have so far:
private static IEnumerable<Cow> ReadCowStream(Stream source)
{
bool isHeader = true;
var cows = new List<Cow>();
using (var reader = new StreamReader(source))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != null)
{
var values = line.Split(',');
if (isHeader && values.Contains("Weight") && values.Contains("Age"))
{
isHeader = false;
}
else
{
cows.Add(new Cow(
weight: values[0],
age: values[1]));
}
}
}
}
return animals;
}
Example CSV:
Weight,Age
300,10
319,11
100,1
370,9
In this case the output would be a List<Cow> with the first entry having values "Weight": "300" and "Age": "10" obviously, but what if "Weight" and "Age" are reversed? Then I'll assign the wrong values to the wrong variables.
Basically, I want to use the headers for determining whether to put values[0] into weight or age etc., as I assume I can't be guaranteed which comes first in the CSV I'm reading.
if(header[0] == 'Weight')[...] else [...]that would be the easiest i'd say.