-1

I have a method that cycles through a csv file to find the closest data point to co-ordinates the user has entered, and I have set rowCounter to keep track of which row of data I will need, however I can't find how I can use CsvHelper to read the 3rd column of the 48th row for example.

Thanks.

hiling99
  • 1
  • 3
  • Post the code please. – Oliver Weichhold Oct 24 '22 at 16:03
  • To read to a specific cell (e.g. the 3rd column cell) with CsvHelper see [Issue getting cell value from CSV file using CsvHelper](https://stackoverflow.com/q/50981386/3744182). To read to a specific row can't you just do `csvReader.Read()` until you reach that row? What exactly is your problem with reading to a specific row? Does your CSV file have a header? Can you share a [mcve] showing what you have tried and where you are stuck? – dbc Oct 24 '22 at 17:57
  • 1
    Use the example in the documentation (https://joshclose.github.io/CsvHelper/examples/reading/reading-by-hand/). You'll need to iterate with a counter, or read the entire thing into a List/Array and access via index. – eriyg Oct 24 '22 at 19:25
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 24 '22 at 20:58

1 Answers1

0

This is one way you could do it.

void Main()
{
    var rowCounter = 2;
    var column = 3;
    
    using (var reader = new StringReader("Id,Name,Coord\n1,MyName,\"33.58031909940288,-7.605511124945705\"\n2,TheirName,\"38.89771555435096,-77.03653334423834\""))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Read();
        csv.ReadHeader();
        
        var count = 1;
        var result = string.Empty;
        
        while (csv.Read() && count <= rowCounter)
        {
            if (count == rowCounter)
            {
                result = csv.GetField<string>(column - 1);
            }
            
            count++;
        }
        result.Dump();
    }
}
David Specht
  • 7,784
  • 1
  • 22
  • 30