Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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] .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading