收到 的错误.在 foreach 循环中使用 lambda 表达式来表示无效参数

本文关键字:表达式 lambda 表示 参数 无效 错误 foreach 循环 收到 | 更新日期: 2023-09-27 18:35:48

我正忙于在VS2010中创建索引Windows表单应用程序的文件/文件夹(大学作业)。出于测试目的,文件/文件夹索引类位于控制台应用程序中

我使用以下方法浏览文件夹,它运行良好并写入指定驱动器中的所有文件夹名称。我主要从 msdn 资源(使用递归方法)中将其放在一起,并进行了修改,因为它不包括获取文件夹名称。

我想排除某些文件夹,并决定使用 lambda 表达式和带有单词列表的列表将是最快的,尽管我可以放置一个循环,通过一个带有 if 比较的数组,但在我看来这会更慢(不是我对 c# 中复杂的工作原理有足够的了解)。我简要地查看了 lambda 表达式,看看我自己是否无法修复它。

这是我的代码,没有任何文件夹排除

class Program
{
    static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
    private static List<string> _excludedDirectories = new List<string>() { "Windows", "AppData", "$WINDOWS.~BT", "MSOCache", "ProgramData", "Config.Msi", "$Recycle.Bin", "Recovery", "System Volume Information", "Documents and Settings", "Perflogs" };
    //method to check
    static bool isExcluded(List<string> exludedDirList, string target)
    {
        return exludedDirList.Any(d => new DirectoryInfo(target).Name.Equals(d));
    }
    static void Main()
    {
        string[] drives = {"C:''"};
        foreach (string dr in drives)
        {
            DriveInfo di = new System.IO.DriveInfo(dr);
            // Here we skip the drive if it is not ready to be read. 
            if (di.IsReady)
            {
                DirectoryInfo rootDir = di.RootDirectory;
                WalkDirectoryTree(rootDir);
            }
            else
            {
                Console.WriteLine("The drive {0} could not be read", di.Name);
                continue;
            }
        }
        // Write out all the files that could not be processed.
        Console.WriteLine("Files with restricted access:");
        foreach (string s in log)
        {
            Console.WriteLine(s);
        }
        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key");
        Console.ReadKey();
    }
    static void WalkDirectoryTree(System.IO.DirectoryInfo root)
    {
        FileInfo[] files = null;
        DirectoryInfo[] subDirs = null;
        StreamWriter filex = new System.IO.StreamWriter("test.txt", true);
        if (filex != null)
        {
            filex.Close();
        }
        // Process all the folders directly under the root 
        try
        {
            subDirs = root.GetDirectories();
        }// This is thrown if even one of the folders requires permissions greater than the application provides. 
        catch (UnauthorizedAccessException e)
        {
            log.Add(e.Message);
        }
        catch (System.IO.DirectoryNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        // Process all the files directly under the root 
        try
        {
            files = root.GetFiles("*.*");
        }// This is thrown if even one of the files requires permissions greater than the application provides. 
        catch (UnauthorizedAccessException e)
        {
            log.Add(e.Message);
        }
        catch (System.IO.DirectoryNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
        if (files != null)
        {
            filex = new StreamWriter("test.txt", true);
            foreach (FileInfo fi in files)
            {
                // In this example, we only access the existing FileInfo object. If we 
                // want to open, delete or modify the file, then 
                // a try-catch block is required here to handle the case 
                // where the file has been deleted since the call to TraverseTree().
                Console.WriteLine(fi.FullName);
                filex.WriteLine(fi.FullName);
            }
            filex.Close();
        }
        if (subDirs != null)
        {
            //var filteredDirs = Directory.GetDirectories(root.Name).Where(d => !isExcluded(_excludedDirectories, d));
            foreach (DirectoryInfo subds in subDirs)
            {
                filex = new StreamWriter("test.txt", true);
                Console.WriteLine(subds.FullName);
                filex.WriteLine(subds.FullName);
                filex.Close();
                foreach (DirectoryInfo dirInfo in subDirs)
                {
                    // Resursive call for each subdirectory.
                    WalkDirectoryTree(dirInfo);
                }
            }
            filex.Close();// Because at end filestream needs to close
        }
    }
}

所以我尝试合并.其中(d => !isExcluded(_excludedDirectories, d)) 进入我的循环:

if (subDirs != null)
        {
            //var filteredDirs = Directory.GetDirectories(root.Name).Where(d => !isExcluded(_excludedDirectories, d));
            foreach (DirectoryInfo subds in subDirs.Where(d => !isExcluded(_excludedDirectories, d)))
            {
                filex = new StreamWriter("test.txt", true);
                Console.WriteLine(subds.FullName);
                filex.WriteLine(subds.FullName);
                filex.Close();
                foreach (DirectoryInfo dirInfo in subDirs)
                {
                    // Resursive call for each subdirectory.
                    WalkDirectoryTree(dirInfo);
                }
            }
            filex.Close();// Because at end filestream needs to close
        }

问题:我在感叹号后收到一个错误,说"最佳重载方法匹配有一些无效的参数..."我应该做什么/更改,我应该采取更简单的路线并在循环中使用循环和 if 语句来写入文件夹名称?因为我也知道如何做到这一点。请记住,我目前的做法(至少尝试)是因为我认为它会更优化/更快。如果它没有这么大的区别,请告诉我,我会使用我知道的方式。

我的猜测是,我试图在foreach中放置一个.where,这是一件坏事,我意识到为什么会或可能是这样。

我也试过:

if (subDirs != null)
        {
            //var filteredDirs = Directory.GetDirectories(root.Name).Where(d => !isExcluded(_excludedDirectories, d));
            foreach (DirectoryInfo subds in subDirs)
            {
              if ((d => !isExcluded(_excludedDirectories, d)))
              {
                filex = new StreamWriter("test.txt", true);
                Console.WriteLine(subds.FullName);
                filex.WriteLine(subds.FullName);
                filex.Close();
                foreach (DirectoryInfo dirInfo in subDirs)
                {
                    // Resursive call for each subdirectory.
                    WalkDirectoryTree(dirInfo);
                }
              } 
            }
            filex.Close();// Because at end filestream needs to close
        }

但是收到有关无法将 lamba 表达式转换为 bool 类型的错误,因为它不是委托

如果您想查看其他代码,请告诉我,然后我会添加它,只是看起来有点多。

收到 的错误.在 foreach 循环中使用 lambda 表达式来表示无效参数

d在这里不是string,而是DirectoryInfo。更改isExcluded方法签名以正确处理d类型。

您的签名是:

static bool isExcluded(List<string> exludedDirList, string target)

它应该是:

static bool isExcluded(List<string> exludedDirList, DirectoryInfo target)

您的方法最终将是:

//method to check
static bool isExcluded(List<string> exludedDirList, DirectoryInfo target)
{
    return exludedDirList.Any(d => target.Name.Equals(d));
}

问题就在这里:

foreach (DirectoryInfo subds in subDirs.Where(d => !isExcluded(_excludedDirectories, d)))

subDirs 的类型是 DirectoryInfo,你的 isExcluded 接受一个字符串作为第二个参数。

你想要:

foreach (DirectoryInfo subds in subDirs.Where(d => !isExcluded(_excludedDirectories, d.Name)))