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