1

我想知道我的以下代码是否有更好的替代方案(最好使用 LINQ)

            #region List and filter directories to only 3 levels deep
            // List all subdirectories within main directory
            string[] folders = Directory.GetDirectories(@"C:\pdftest\", "*" ,SearchOption.AllDirectories);
            List<string> subdirectories = new List<string>();

            //Filter away all main directories, now we are left with subdirectories 3 levels deep
            for (int i = 0; i<folders.Length; i++)
            {
                int occurences = folders[i].Split('\\').Length-1;
                if (occurences==4)
                    subdirectories.Add(folders[i]);             
            }
            #endregion
4

2 回答 2

2

未经测试,但应该这样做。

        string[] subDirectories = Directory.GetDirectories(@"C:\pdftest\", "*", SearchOption.AllDirectories).Where(folder => folder.Split('\\').Length <= 4).ToArray();
于 2010-05-06T09:01:53.927 回答
0

根据Oliver的评论,重要的是检查您使用所谓的“根”默认路径的深度。

string Root = "C:\pdftest\".TrimEnd('\\');
int RootLength = Root.Split('\\').Length;
string[] subDirectories = Directory.GetDirectories(@"C:\pdftest\", "*", SearchOption.AllDirectories).Where(folder => folder.Split('\\').Length <= RootLength+4).ToArray();
于 2021-04-21T10:28:57.173 回答