Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

line number while querying with linq

I am using a stream reader to read a text file and then using Linq for retrieving the information

String fileContent = prodFileStreamReader.ReadToEnd();

 var mydata = from con in fileContent.Split('$').Select(x => x.Trim())
                    where !String.IsNullOrEmpty(con)
                    select new BaseSegment
                    {
                      dataID = con.Substring(0, con.IndexOf('#')),
                      dataElms = con.Split('#').ToArray(),
                      dataCon = con,
           lineNumber = 
                    };

I would also like to get the line number. I tried using Index but I was not able to. How to query to get the index and assign it to lineNumber?

like image 661
user425381 Avatar asked Aug 11 '11 07:08

user425381


2 Answers

Try using the select that projects index into each item, as given in this msdn article: http://msdn.microsoft.com/en-us/library/bb534869.aspx

In your case something like this (not tested):

var mydata = fileContent.Split('$')
             .Select(x => x.Trim())
             .Where(con => !String.IsNullOrEmpty(con))
             .Select((con, index) => new
                             {
                                 dataID = con.Substring(0, con.IndexOf('#')),
                                 dataElms = con.Split('#').ToArray(),
                                 dataCon = con,
                                 lineNumber = index
                             });
like image 161
Andreas Ågren Avatar answered Sep 29 '22 10:09

Andreas Ågren


For starters, I would not read the file in as a big string. Use methods that could process it in small chunks. Use File.ReadLines() for example to read through the file line by line. It will be easier to get line numbers this way and much more efficient than reading it all at once only to split it up again.

const string filePath = ...;
var myData =
    from pair in File.ReadLines(filePath)
                     .Select((LineNumber, Line) => new { LineNumber, Line })
    where ...
    select new BaseSegment
    {
        ...
        Line = pair.Line,
        LineNumber = pair.LineNumber,
    };

p.s., You should stick to the usual C# naming conventions. Public properties of your classes should use PascalCasing, not camelCasing and should not be abbreviated.

The code you use to process the content looks awkward. It could probably be improved if I knew what the files looked like. I'll leave that out until you could show us how it is.

like image 27
Jeff Mercado Avatar answered Sep 29 '22 08:09

Jeff Mercado