2

我正在尝试检查所有需要的子目录是否存在并为此使用这段代码:

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 语句的最佳方法是什么?

4

4 回答 4

4

你可以这样做

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


}

等等

于 2013-07-11T13:10:15.677 回答
2

你可以反过来做:

   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
    }
于 2013-07-11T13:18:33.750 回答
1

以琼斯的所作所为为基础,

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
}

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

于 2013-07-11T13:33:48.487 回答
1
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
}
于 2013-07-11T13:13:27.557 回答