Hakunama Tatarov
Hakunama Tatarov

Reputation: 125

How to get row count using LINQ on a file

I have the following Code so far:

var lines = from rawLine in File.ReadLines(readFolderFile, Encoding.Default) where !string.IsNullOrEmpty(rawLine) && !string.IsNullOrEmpty(rawLine.Trim(';')) select rawLine;

But now I also need in the first "colum" of my IEnumerable the row count. I tried to adapt from other people who had a more or less similar problem but never got it to work so far.

I tried "solutions" like: How do you add an index field to Linq results , Get record's row number using Linq and some other ones. I do unterstand, that I need some kind of index, but I dont understand where do I add my .Select(()=> )

What I tried and obsiously doesnt work is:

var lines = (from rawLine in File.ReadLines(readFolderFile, Encoding.Default) where !string.IsNullOrEmpty(rawLine) && !string.IsNullOrEmpty(rawLine.Trim(';'))
            select rawLine).Select((rawLine, index) =>  index++, rawLine);

Upvotes: 0

Views: 1083

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460058

Query syntax doesn't provide the overload of Select (and Where) with the index. So you need to use method syntax.

If you also want to count empty lines but don't include them in the result, select the anonymous type before the Where otherwise after:

var linesAndLineNumbers = File.ReadLines(readFolderFile, Encoding.Default) 
   .Select((line, index) => new { Line = line.Trim(';'), LineNumber = index + 1 })
   .Where(x => !String.IsNullOrWhiteSpace(x.Line));

is there a way, where I could get the result as Line = {Line = "LineNumer;colum1;colum2;columnX..."}

Sure:

var lines = File.ReadLines(readFolderFile, Encoding.Default) 
   .Select((line, index) => new { Line = line.Trim(';'), LineNumber = index + 1 })
   .Where(x => !String.IsNullOrWhiteSpace(x.Line))
   .Select(x => $"{x.LineNumber};{x.Line};");

Upvotes: 2

Dmitry Korolev
Dmitry Korolev

Reputation: 675

You indeed need to use Select, and then just to store the index.

var lines = File.ReadLines(readFolderFile, Encoding.Default)
    .Where(x => !string.IsNullOrEmpty(rawLine) && !string.IsNullOrEmpty(rawLine.Trim(';')))
    .Select((x, i) => new
    {
        Line = x,
        Index = i
    }
    .ToList();

Upvotes: 2

Related Questions