3

I am reading a text file using File.ReadAllLines(), but I can also use File.ReadLines(). After I read the file, the next step is creating a list from the result. In my list I need to get the line number for each entry/row in the text file. Can this be done? How? For my end result I need my list to have an Index property.

Here's what I've got:

var file = System.IO.File.ReadAllLines(path);

var lineInfo = file.AsParallel().AsOrdered()
    .Select(line => new
    {     
       // index =  **** I WANT THE INDEX/ROWNUMBER HERE ****
       lineType = line.Substring(0, 2),
       winID = line.Substring(11, 9),
       effectiveDate = line.Substring(0, 2) == EmployeeLine ? line.Substring(237, 8).ToDateTimeExact("yyyyMMdd") : null,
                    line
     })
     .ToList()
     .AsParallel();
Big Daddy
  • 5,160
  • 5
  • 46
  • 76
  • 4
    Given that you are only going to be iterating the result, you should be using `File.ReadLines` instead so that you can stream the input, rather than forcing it all to be loaded into memory needlessly. It's also likely worthwhile to avoid materializing the result of the operation into a list, unless you truly need to do so. – Servy Jun 11 '14 at 15:37

2 Answers2

4

Select has an override that supplies the index.

You should therefore be able to change your select to include it:

var lineInfo = file.AsParallel().AsOrdered()
    .Select((line, index) => new
    {     
         ....
    }
 })
 .ToList()
 .AsParallel();

However, as Servy points out in his comment, if you are going to load the whole file, only to iterate over it again after, then you may as well process each line in a streaming manner.

Always useful to learn about new bits of the framework though.

Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
1

You could try this one:

.Select((line,index) => new
{     
   Index = index
   lineType = line.Substring(0, 2),
   // the rest of your code.
 })

Also here is a link, in which this is used.

Christos
  • 53,228
  • 8
  • 76
  • 108