gpt4 book ai didi

c# - 重构:计算给定文件夹下所有文件的总行数

转载 作者:太空狗 更新时间:2023-10-30 00:16:10 24 4
gpt4 key购买 nike

我写了一段代码来计算给定文件夹中所有文件的行数。它工作正常,但我正在尝试包括所有可能的 C# 功能以将其重构为更紧凑和高效的代码。请帮我做到这一点。

这是代码。

    class LineNumberCounter
{
public static string Calculate(string folderPath, string pattern = "*.txt")
{
DirectoryInfo dirInfo = new DirectoryInfo(folderPath.Trim());
if (!dirInfo.Exists)
throw new ArgumentException("No such directory exists");

StringBuilder returnValue = new StringBuilder();
long totalLines = 0;

pattern.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).All(filter =>
{
int count = 0;
dirInfo.GetFiles(filter.Trim(),
SearchOption.AllDirectories).All(file =>
{
using (StreamReader reader = file.OpenText())
{
for (; reader.Peek() > -1; count++)
reader.ReadLine();
}
returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}",
filter, count));
totalLines += count;

return true;
}
);

return true;
});

//foreach (string filter in
// pattern.Split(new char[] { ';' },
// StringSplitOptions.RemoveEmptyEntries))
//{
// FileInfo[] files = dirInfo.GetFiles(filter.Trim(),
// SearchOption.AllDirectories);
// int count = 0;
// Array.ForEach<FileInfo>(files, file =>
// {
// using (StreamReader reader = file.OpenText())
// {
// for (; reader.Peek() > -1; count++)
// reader.ReadLine();
// }
// });

// returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}",
// filter, count));
// totalLines += count;
//}

returnValue.AppendLine();
returnValue.AppendLine("Total Lines = " + totalLines);

return returnValue.ToString();
}
}

注释行是我最初写的。我尝试重构它。但仍然想检查它是否有更多范围。

最佳答案

使用新的 >=.NET 4 方法 File.ReadLines()

int total = File.GetFiles(folderPath, pattern)
.Sum(x => File.ReadLines(x).Count());

来自 MSDN 的一些注意事项:

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

关于c# - 重构:计算给定文件夹下所有文件的总行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com