Chandana Chandana - 2 months ago 11
C# Question

c# parallel foreach loop finding index

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();

Answer

There is another overload for Parallel.ForEach that gives you the index. See https://msdn.microsoft.com/en-us/library/dd783359(v=vs.110).aspx

Parallel.ForEach(list_lines, (line, state, index) =>
    {
        Console.WriteLine(index);
        Console.WriteLine(list_lines[index]);
    });
Comments