-6

I have seen the following code used in other posts and it seems to be accepted as an answer but when I use it, it doesn't work correctly. Its purpose is to pull the last three lines of a text file and output them to the user.

I do not receive any build errors, but the console doesn't output the contents of the given .csv.

List<string> test = File.ReadAllLines("test.csv").Reverse().Take(3).Reverse().ToList();

Console.WriteLine(test);

EDIT:

This posted without the full post.

The contents of the csv are numbers 0-10 and I need to pull the last three numbers of the file upon request.

For testing purposes, the csv is currently laid out:

1
2
3
4
5

I want to pull the numbers in the order of 3, 4, 5.

benf
  • 77
  • 1
  • 1
  • 12

4 Answers4

1

What you're WriteLineing is a value of List<string>.ToString(), which is not what you want. Try foreaching over the test list and WriteLine each line separately.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
1
foreach(var item in test )
{
Console.WriteLine(item);
}
Bayu Alvian
  • 171
  • 5
0

Your example will print something like "System.Collections.Generic.List'1[System.String]" This is because the Console.WriteLine() is expecting a string (which it may be receive using the object's ToString() method) yet you pass it a List<> object whose ToString() method returns "System.Collections.Generic.List'1[System.String]".

Instead you need to retrieve each string from the list with a foreach loop and then print each string as you retrieve it.

For Example:

var lst = new List<string>();

lst.Add("test1");
lst.Add("test2");
lst.Add("test3");           

foreach (var item in lst)
{
    Console.WriteLine(item); // item, not list
}
Console.Read();
benf
  • 77
  • 1
  • 1
  • 12
Ryan Searle
  • 1,597
  • 1
  • 19
  • 30
-1

You can do it like this:

using System.IO;

static void Main(string[] args)
{
    var reader = new StreamReader(File.OpenRead(@"C:\test.csv"));
    List<string> listA = new List<string>();
    List<string> listB = new List<string>();
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        var values = line.Split(';');

        listA.Add(values[0]);
        listB.Add(values[1]);
    }

    foreach(var item in listA )
    {
       Console.WriteLine(item);
    }

    foreach(var item in listB )
    {
       Console.WriteLine(item);
    }
}

Link to the Answer

Community
  • 1
  • 1
ascholz
  • 179
  • 1
  • 9