winforms 在C#中,有没有比使用嵌套ifs更好的方法来检查多个子目录的存在性?

u0sqgete  于 2022-12-04  发布在  C#
关注(0)|答案(4)|浏览(398)

我尝试使用以下代码片段检查是否存在所有需要的子目录:

DirectoryInfo gccdir = new DirectoryInfo(txtgccPath.Text);
List<string> subdirectories = new List<string>();

foreach (var item in gccdir.GetDirectories())
{
   subdirectories.Add(item.Name);
}

if (subdirectories.Contains("bin") &&
    subdirectories.Contains("i686-w64-mingw32") &&
    subdirectories.Contains("include") && 
    subdirectories.Contains("lib") &&
    subdirectories.Contains("libexec") && 
    subdirectories.Contains("share"))
{
  //statements 
}

有没有更好的方法?在这种需要验证多个条件的情况下,避免过度使用if else语句的最佳方法是什么?

0md85ypi

0md85ypi1#

你可以这样做

if(new[] {"bin", "include", "lib"}.All(subdirectories.Contains))
{

}

等等。

xqnpmsa8

xqnpmsa82#

你可以反过来做:

DirectoryInfo gccdir = new DirectoryInfo(txtgccPath.Text);
    List<string> directorieslist=new List<string>(){"bin", "i686-w64-mingw32","include", "lib","libexec","share"};

    foreach (var item in gccdir.GetDirectories())
    {
        if(directorieslist.Contains(item.Name))
        {
             directorieslist.Remove(item.Name);                         
        } 
    }

    if(directorieslist.Count==0)
    {
       //statement
    }
06odsfpq

06odsfpq3#

string[] subs = new string[] {
    "bin",
    "i686-w64-mingw32",
    "include"
    };

IEnumerable<string> exists = subdirectories.Join(subs, 
    sd1 => sd1, 
    sd2 => sd2, 
    (sd1, sd2) => sd1).ToArray();

if (subs.Length == exists.Length)
{
// contains all
}
cgyqldqp

cgyqldqp4#

根据琼西的所作所为

DirectoryInfo gccdir = new DirectoryInfo(txtgccPath.Text);
var subdirectories= gccdir.GetDirectories();
var dirsToCheckFor = new[] { "bin", "include", "lib", "libexec", "share", "i686-w64-mingw32" };

if(subdirectories.All(dir => dirsToCheckFor.Contains(dir.Name)))
{
    //gccdir contains all folders in dirsToCheckFor
}

唯一的区别是,您不需要为文件夹中的目录创建字符串列表。

相关问题