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?
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
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With