Reputation: 14112
In my program I want to import csv files that only should have a pair of doubles in them. Something like:
2.2131321321, 32.321321321
3.31321321321, 65.65454545
4.12321351351, 16.13211212
Can you help finding out a safe and fast way of doing so?
Upvotes: 1
Views: 275
Reputation: 56172
The easiest way is read file line by line, split every line by ,
and try to parse each part using double.TryParse
Simple sample, assuming that file is valid (without check):
public static IEnumerable<Tuple<double, double>> ReadCSV(string filePath)
{
using (var reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
var split = line.Split(new[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
yield return new Tuple<double, double>(
double.Parse(split[0], CultureInfo.InvariantCulture),
double.Parse(split[1], CultureInfo.InvariantCulture));
}
}
}
Upvotes: 4