0


I have a csv file that I need to read one line at a time and fill .net objects from it (first line header).
Now, I know I can do it via ReadLine and then assign the object properties but I was wondering if there's any shorter way of doing it.
I tried using LINQ but that reads all the lines at ones
File.ReadAllLines("C:\\....csv").Skip(1)...
Please advice. Thanks.

Amar
  • 303
  • 1
  • 3
  • 19

1 Answers1

1

yep Ivan say it, use ReadLines()

for reading header and data in one access you can use the old school Enumerator:

static void Main(string[] args)
{
  var enumerator = File.ReadLines("foo.csv").GetEnumerator();

  enumerator.MoveNext();
  string headerLine = enumerator.Current; // null if file empty

  while (enumerator.MoveNext())
  {
    string dataLine = enumerator.Current;
  }
}

or after the headline you can convert the Enumerator to IEnumerable<> back:

static IEnumerable<T> AsEnumerable<T>(IEnumerator<T> enumerator)
{
  while (enumerator.MoveNext()) yield return enumerator.Current;
}

and replace the while loop with var query = AsEnumerable(enumerator);

MaxKlaxx
  • 713
  • 7
  • 9