I wrote code to count the number of lines in all files in a given folder. It works great, but I'm trying to incorporate all the possible features of C # to reorganize it into more compact and efficient code. Please help me do this.
Here is the code.
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; });
The commented lines were the ones I originally wrote. I tried to reorganize it. But still want to check if it has more features.
source share