Line number when querying with linq

I use a stream reader to read a text file and then using Linq to extract 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 could not. How to query to get an index and assign it to a row?

+5
source share
5 answers

Try using an index that indexes projects for each item, as indicated in this msdn article: http://msdn.microsoft.com/en-us/library/bb534869.aspx

In your case, something like this (not verified):

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
                             });
+7
source

How about this?

var animalList = from a in animals
                         select new { Animal = a, Index = animals.IndexOf(a) };

or in your case ...

Index = fileContent.IndexOf(con)
0
source

myData, myData.

0

-, . , . File.ReadLines(), , . , , .

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., #. PascalCasing, camelCasing .

, , . , , , . , , .

0

-

long index = 0;
var xElementsAndNodes = from xmlElement in elementsColl
select new
{
  Index = index += 1,
  ....
}
-1

All Articles