none
How to console.writeline the last line of a List<> c#

    Question

  • Hi I have a list of strings that I read from a text file into a list. I know how to write these to console using a for loop or a foreach statement but how would I write only the last line of the list to console?

    List<string> DataFile = File.ReadLines.ToList();
    foreach (string line in DataFile)
             {
              Console.WriteLine(line);
             }
    
    Which gives me:
    00005: r1: race HHE
    00006: r1 race HHE
    000012: r5 race EFD
    
    This is an example of output on a much smaller scale, in total there are approximately 200 lines of output. I only want the last line to show in console. How do I do this?



    Wednesday, April 19, 2017 7:06 PM

Answers

  • Try this

    List<string> sample = new List<string>() {"First","Second", "Third" };
    
    Console.WriteLine(sample.Last());
    Console.ReadLine();


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Proposed as answer by Ehsan Sajjad Wednesday, April 19, 2017 8:30 PM
    • Marked as answer by CuriousCoder79 Thursday, April 20, 2017 8:06 AM
    Wednesday, April 19, 2017 7:52 PM
    Moderator
  • Hi CuriousCoder79,

    Thank you for posting here.

    For your question, you could use Last() method or LastOrDefult() method to get what you want.

    Here is a simple code for reference.

       List<string> DataFile = File.ReadLines(@"C:\Users\v-wezan\Desktop\N1.txt").ToList();
                Console.WriteLine(DataFile.Last());
                Console.WriteLine(DataFile.LastOrDefault());
                Console.ReadKey();

    I hope this would be helpful.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, April 20, 2017 2:11 AM
    Moderator
  • Hello,

     You can try the below code;

    Console.WriteLine( DataFile[ DataFile.Length - 1 ] );

    Remember, containers still allow indexer access, Object [ ], but you must

    keep in mind that this method does not prevent Out Of Range Errors. Where

    IEnumerable from ForEach does.

     Hope this helps :)

    • Proposed as answer by Ehsan Sajjad Wednesday, April 19, 2017 8:30 PM
    • Marked as answer by CuriousCoder79 Thursday, April 20, 2017 8:15 AM
    Wednesday, April 19, 2017 7:35 PM

All replies

  • Hello,

     You can try the below code;

    Console.WriteLine( DataFile[ DataFile.Length - 1 ] );

    Remember, containers still allow indexer access, Object [ ], but you must

    keep in mind that this method does not prevent Out Of Range Errors. Where

    IEnumerable from ForEach does.

     Hope this helps :)

    • Proposed as answer by Ehsan Sajjad Wednesday, April 19, 2017 8:30 PM
    • Marked as answer by CuriousCoder79 Thursday, April 20, 2017 8:15 AM
    Wednesday, April 19, 2017 7:35 PM
  • Try this

    List<string> sample = new List<string>() {"First","Second", "Third" };
    
    Console.WriteLine(sample.Last());
    Console.ReadLine();


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Proposed as answer by Ehsan Sajjad Wednesday, April 19, 2017 8:30 PM
    • Marked as answer by CuriousCoder79 Thursday, April 20, 2017 8:06 AM
    Wednesday, April 19, 2017 7:52 PM
    Moderator
  • Hi CuriousCoder79,

    Thank you for posting here.

    For your question, you could use Last() method or LastOrDefult() method to get what you want.

    Here is a simple code for reference.

       List<string> DataFile = File.ReadLines(@"C:\Users\v-wezan\Desktop\N1.txt").ToList();
                Console.WriteLine(DataFile.Last());
                Console.WriteLine(DataFile.LastOrDefault());
                Console.ReadKey();

    I hope this would be helpful.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, April 20, 2017 2:11 AM
    Moderator
  • These solutions all work to show the last line, Thank you.

    If I nest 2 if statements in the for each loop like so;

     string pL = "";
    
                    if (pL.Contains("Data"))
                    {
                        if (line.Contains("Final"))
                        {
                            Console.WriteLine(pL);
                            
                         Console.WriteLine(DataFile.Last());
                        }
                        
                    }
                    pL = line;
    It is now difficult to get the last line because I am looking at 2 lines; line and pL (previous line). If I use the Last() Method here I only get the last character of pL and it is repeated many times. Is it possible to get the last pL in the list?




    Thursday, April 20, 2017 8:13 AM
  • Hello,

    First off when asking a question here it's prudent to supply all details up front instead of coming up with another requirement after the fact.

    Looking at your last reply, you have set pl to an empty string then immediately use Contains where how it's written it's not possible for pl to contain anything.

    So this will go to the else

    List<string> sample = new List<string>()
    {
        "First",
        "Second Data and Final work",
        "Third"
    };
    
    var pl = "";
    
    if (pl.Contains("Data"))
    {
        Console.WriteLine("Found data");
    }
    else
    {
        Console.WriteLine("Did not find data");
    }

    We could do this if one line is expected

    List<string> sample = new List<string>()
    {
        "First",
        "Second Data and Final work",
        "Third",
        "Final Data"
    };
    
    
    var word1 = "Data";
    var word2 = "Final";
    
    var results = sample
        .Select((line, index) => new { Line = line, Index = index })
        .Where(item => item.Line.Contains(word1) && item.Line.Contains(word2));
    
    if (results.Count() == 1)
    {
        Console.WriteLine($"Line {results.First().Index} contains '{word1}' and '{word2}'");
    }
    else
    {
        Console.WriteLine("Not found");
    }

    Or if multiple lines are expected

    List<string> sample = new List<string>()
    {
        "First",
        "Second Data and Final work",
        "Third",
        "Final Data"
    };
    
    
    var word1 = "Data";
    var word2 = "Final";
    
    var results = sample
        .Select((line, index) => new { Line = line, Index = index })
        .Where(item => item.Line.Contains(word1) && item.Line.Contains(word2));
    
    
    if (results.Count() >0)
    {
        foreach (var item in results)
        {
            Console.WriteLine($"Line {item.Index} contains '{word1}' and '{word2}'");
        }
    }
    So please provide more details as I mentioned above  the code shown does not make sense.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, April 20, 2017 9:39 AM
    Moderator
  • Sorry to have angered you Karen, that was not my intention. I am new to programming so my questions may not be to the point but, I am researching as much as possible before asking a question and only then if I cannot find something that I understand will I pose a question to this forum. 

    I did not know that the scenario of nesting if statements to read 2 lines at the same time then try to output the last line wouldn't work. As I am new I took smaller steps and asked how to console.WriteLine the last line.

    I now realise that I should perhaps save these results to another list then use the Last() method. It is through making a mistake that I arrived at this possible solution.

    When learning it's asking questions and making mistakes that aid in learning. If this forum is meant for professionals that know exactly the right question to ask and not for learners such as myself then I will not ask anymore.

    Thank you for your time







    Thursday, April 20, 2017 10:00 AM
  • Hi,

    First off you didn't anger me, instead I was providing insight.

    Here is how I would ask a question. Describe what I'm doing and where I'm stuck. When explaining what I'm doing means write out in English without code the task and what I want then show code to backup the task if there is any code.

    So when I in my last reply the variable pl being set to an empty string then attempting to see if the variable contains a specific word didn't make any sense but if you had shown that pl may of had something in it that would be different.

    The forums are for all levels of developers or hobbyist so keep on asking.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, April 20, 2017 10:54 AM
    Moderator