Sar*_*gam 4 c# refactoring .net-4.0
我编写了一个代码来计算给定文件夹中所有文件的行数.它工作正常,但我试图包含所有可能的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();
}
}
Run Code Online (Sandbox Code Playgroud)
注释行是我最初写的.我试图重构它.但仍想检查是否有更多范围.
sll*_*sll 10
使用新>=.NET 4方法File.ReadLines()
int total = File.GetFiles(folderPath, pattern)
.Sum(x => File.ReadLines(x).Count());
Run Code Online (Sandbox Code Playgroud)
MSDN的一些注意事项:
ReadLines和ReadAllLines方法的不同之处如下:使用ReadLines时,可以在返回整个集合之前开始枚举字符串集合; 当您使用ReadAllLines时,必须等待返回整个字符串数组才能访问该数组.因此,当您使用非常大的文件时,ReadLines可以更高效.
| 归档时间: |
|
| 查看次数: |
676 次 |
| 最近记录: |