Skip to main content
 首页 » 编程设计

c#之计算文本文件中满足条件的行数

2024年02月06日1398°冷暖

我有 2 个来自 Microsoft 的 LINQ 示例的脚本。第一个将计算文本文件中的所有文本行。第二个将仅列出满足特定条件的记录。

如何将相同的条件应用于第一个计数脚本?

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)); 

请您参考如下方法:

How can I apply the same condition to the first counting script?

像这样:

int numberOfRecords = records.Count(x => x.Line.Contains(".dwg")); 

想法是更改您正在调用的方法:而不是无参数* 方法,调用overload that takes a condition .

* 从技术上讲,Count() 采用单个参数 - 它所应用的列表。该参数是不可见的,因为它是使用扩展方法语法隐式传递的。