I was writing some code today to map online drive and files to a local objecttree. So I created a custom file and directory object and a directory holds subdirectories and files.
Something like this:
public class File{ public string Name { get; set; }}
public class Directory{ public string Name { get; set; } public List<Directory> SubDirectories { get; set; } public List<File> Files { get; set; }}
Now I wanted to have a method which tells me how many files are in a folder, including all the subfolders. This is essentially a recursive select of the number of files per directory and then the sum of the files.
So I implemented a LINQ statement:
public int GetNumberOfFiles(){ int total = ( from dir in SubDirectories select dir.Files.Count ).Sum(); return total;}
Now this will only get the sum of the number of files in the directories immediately below the current. Let's add a little recursion:
public int GetNumberOfFiles(){ int total = ( from dir in SubDirectories select dir.Files.Count + dir.GetNumberOfFiles() ).Sum(); return total;}
Pretty nifty!