Problem using System.Linq to print a file line by line (C#)

So I’m writing a very simple way to display graphics content in a text file (Just unicode symbols) line by line, at a certain distance from the console edge.

GraphicsDraw:
int GraphicsDrawCount = 0;
do
{
    Console.SetCursorPosition(3, 3 + GraphicsDrawCount);

    TempMemory = Convert.ToString(File
      .ReadLines("F:\\Assets\\StartScreen.txt")
      .Skip(GraphicsDrawCount)
      .Take(1)+"");

    Console.WriteLine(TempMemory);
    GraphicsDrawCount++;
} while (GraphicsDrawCount < 19);

I expected it to actually give me the lines in question but instead it constantly outputs

System.Linq.Enumerable+EnumerablePartition`1[System.String] .

Any thoughts on how to fix this?

>Solution :

The immediate cause of misbehavior is that

File
  .ReadLines("F:\\Assets\\StartScreen.txt")
  .Skip(GraphicsDrawCount)
  .Take(1)

returns not a string, but enumeration IEnumerable<string>; so the quick but dirty amendment is to change .Take(1) into .FirstOrDefault(""): we want a single string, not a enumeration of strings with one item.

...
// No need of Convert here
TempMemory = File
  .ReadLines("F:\\Assets\\StartScreen.txt")
  .Skip(GraphicsDrawCount)
  .FirstOrDefault(""); // <- The very first item, instead of Take(1)
...

If you want to print 19 top lines you can just join them:

Console.WriteLine(string.Join(Environment.NewLine, File
  .ReadLines("F:\\Assets\\StartScreen.txt")
  .Take(19)));

Leave a Reply