Reputation: 211
I have 2 scripts from Microsoft's LINQ samples. The first one will count all the lines of text in a text file. The second one will list only the records that meet a certain condition.
How can I apply the same condition to the first counting script?
string[] records = File.ReadAllLines(@"C:\Reports\MyReports.txt");
try
{
int numberOfRecords = records.Count();
Console.WriteLine(
"There are {0} records in the text file.",
numberOfRecords);
}
catch (OverflowException)
{
Console.WriteLine("The count is too large to store as an Int32.");
Console.WriteLine("Try using the LongCount() method instead.");
}
var targetLines = File.ReadAllLines(@"C:\Reports\MyReports.txt")
.Select((x, i) => new { Line = x, LineNumber = i })
.Where( x => x.Line.Contains(".dwg"))
.ToList();
foreach (var line in targetLines)
{
Console.WriteLine("{0} : {1}", line.LineNumber, line.Line);
}
File.WriteAllText (@"C:\Reports\MyReports2.txt", Util.ToCsvString (targetLines));
Upvotes: 1
Views: 725
Reputation: 726499
How can I apply the same condition to the first counting script?
Like this:
int numberOfRecords = records.Count(x => x.Line.Contains(".dwg"));
The idea is to change the method that you are calling: instead of the parameterless* one, call the overload that takes a condition.
* Technically, Count()
takes a single parameter - the list to which it is applied. The parameter is not visible, because it is passed implicitly using the extension method syntax.
Upvotes: 4