Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# parallel foreach loop finding index

Tags:

I am trying to read all lines in a text file and planning to display each line info. How can I find the index for each item inside loop?

string[] lines = File.ReadAllLines("MyFile.txt");
    List<string> list_lines = new List<string>(lines);
    Parallel.ForEach(list_lines, (line, index) =>
      {
         Console.WriteLine(index);
    //   Console.WriteLine(list_lines[index]);
         Console.WriteLine(list_lines[0]);
       });
       Console.ReadLine();
like image 880
Kurkula Avatar asked Sep 26 '16 22:09

Kurkula


1 Answers

There is another overload for Parallel.ForEach that gives you the index.

Parallel.ForEach(list_lines, (line, state, index) =>
    {
        Console.WriteLine(index);
        Console.WriteLine(list_lines[(int)index]); // The type of the `index` is Long.
    });     
like image 74
Curtis Lusmore Avatar answered Sep 16 '22 15:09

Curtis Lusmore