How to replace for-loops with a functional statement in C#?

前端 未结 18 1719
不思量自难忘°
不思量自难忘° 2021-01-31 08:59

A colleague once said that God is killing a kitten every time I write a for-loop.

When asked how to avoid for-loops, his answer was to use a functional language. However

18条回答
  •  时光说笑
    2021-01-31 09:29

    It depends upon what is in the loop but he/she may be referring to a recursive function

        //this is the recursive function
        public static void getDirsFiles(DirectoryInfo d)
        {
            //create an array of files using FileInfo object
            FileInfo [] files;
            //get all files for the current directory
            files = d.GetFiles("*.*");
    
            //iterate through the directory and print the files
            foreach (FileInfo file in files)
            {
                //get details of each file using file object
                String fileName = file.FullName;
                String fileSize = file.Length.ToString();
                String fileExtension =file.Extension;
                String fileCreated = file.LastWriteTime.ToString();
    
                io.WriteLine(fileName + " " + fileSize + 
                   " " + fileExtension + " " + fileCreated);
            }
    
            //get sub-folders for the current directory
            DirectoryInfo [] dirs = d.GetDirectories("*.*");
    
            //This is the code that calls 
            //the getDirsFiles (calls itself recursively)
            //This is also the stopping point 
            //(End Condition) for this recursion function 
            //as it loops through until 
            //reaches the child folder and then stops.
            foreach (DirectoryInfo dir in dirs)
            {
                io.WriteLine("--------->> {0} ", dir.Name);
                getDirsFiles(dir);
            }
    
        }
    

提交回复
热议问题