C# – How to get String Line number in Foreach loop from reading array

arrayscfile-ionetstring

The program helps users to parse a text file by grouping certain part of the text files into "sections" array.

So the question is "Are there any methods to find out the line numbers/position within the array?" The program utilizes a foreach loop to read the "sections" array.

May someone please advise on the codes? Thanks!

namespace Testing
{
class Program
{
    static void Main(string[] args)
    {
        TextReader tr = new StreamReader(@"C:\Test\new.txt");

        String SplitBy = "----------------------------------------";

        // Skip 5 lines of the original text file
        for(var i = 0; i < 5; i++) 
        { 
            tr.ReadLine();
        }

        // Read the reststring 

        String fullLog = tr.ReadToEnd();

        String[] sections = fullLog.Split(new string[] { SplitBy }, StringSplitOptions.None);

        //String[] lines = sections.Skip(5).ToArray();

        int t = 0;

        // Tried using foreach (String r in sections.skip(4)) but skips sections instead of the Text lines found within each sections
        foreach (String r in sections)
        {
            Console.WriteLine("The times are : " + t);

            // Is there a way to know or get the "r" line number?
            Console.WriteLine(r);
            Console.WriteLine("============================================================");
            t++;
        }
    }
}
}

Best Answer

A foreach loop doesn't have a loop counter of any kind. You can keep your own counter:

int number = 1;
foreach (var element in collection) {
  // Do something with element and number,

  number++;
}

or, perhaps easier, make use of LINQ's Enumerable.Select that gives you the current index:

var numberedElements = collection.Select((element, index) => new { element, index });

with numberedElements being a collection of anonymous type instances with properties element and index. In the case a file you can do this:

var numberedLines = File.ReadLines(filename)
                        .Select((Line,Number) => new { Line, Number });

with the advantage that the whole thing is processed lazily, so it will only read the parts of the file into memory that you actually use.