-2

I have a csv file with 2 columns - TreeId and TreeName. How do I read this csv file and select a random line?

user989988
  • 3,006
  • 7
  • 44
  • 91
  • CSV files are just text files with a particular layout. They are not random access. Your app can emulate it by reading the file into a collection and then doing whatever it needs to from there. You will also want to rush to MS Docs and read up on the proper use of `Random` – Ňɏssa Pøngjǣrdenlarp Nov 08 '20 at 19:25
  • Does this answer your question? [Reading CSV files using C#](https://stackoverflow.com/questions/3507498/reading-csv-files-using-c-sharp) – psubsee2003 Nov 08 '20 at 19:44

1 Answers1

3

There is a package CsvHelper that will do all the heavy lifting for you.

To install the package see: https://joshclose.github.io/

Example Code


public class Tree
{
    public int TreeId { get; set; }
    public string TreeName { get; set; }
}

public static void readData()
{
    using (var reader = new StreamReader("input.csv"))
    {
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {    
            var lines = csv.GetRecords<Tree>();
            var random = new Random((int)DateTime.Now.Millisecond);
            var sortedList = lines.OrderBy(x => random.Next()).ToList();
            
            // select random line
            int index = random.Next(lines.Count);
            var randomLine = lines[index];
        }
    }
}

Trekco
  • 1,246
  • 6
  • 17