我正在尝试比较2个文件夹结构,并找到不在另一个树中的最高文件夹。
但是当给出一个例子时,这可能会更清楚: 说我们有这两个文件夹:
Fo1: sub 0 (fo: 3)
> Fo: sub 0 sub 0 (fo: 2)
> > Fo: sub 0 sub 0 sub 0 (fi: 3)
> > Fo: sub 0 sub 0 sub 1 (fi: 3)
> Fo: sub 0 sub 1 (fo: 1)
> > Fo: sub 0 sub 0 sub 0 (fi: 1)
> Fo: sub 0 sub 2 (fo: 2)
> > Fo: sub 0 sub 1 sub 0 (fi: 2)
> > Fo: sub 0 sub 1 sub 1 (fi: 1)
Fo2: sub 0 (fo: 3)
> Fo: sub 0 sub 0 (fo: 1)
> > Fo: sub 0 sub 0 sub 0 (fi: 3)
> Fo: sub 0 sub 1 (fo: 3)
> > Fo: sub 0 sub 1 sub 0 (fi: 1)
> > Fo: sub 0 sub 1 sub 1
> > Fo: sub 0 sub 1 sub 2 (fi: 4)
> Fo: sub 0 sub 2 (fo: 2)
> > Fo: sub 0 sub 2 sub 0 (fi: 1)
> > Fo: sub 0 sub 2 sub 1
结果将是:
Fo: sub 0 sub 1 sub 1
Fo: sub 0 sub 1 sub 2
Fo: sub 0 sub 2
因此,例如,由于已添加了根,因此未添加sub 0 sub 2 sub 0
和sub 0 sub 2 sub 1
。并且sub 0 sub 0
树中没有添加任何内容,因为所有内容都已存在
我尝试了这两种方法:
private static bool compareFolders(Folder folder1, Folder folder2, List<Folder> newFolders, int index = 0) {
// if has a folder that is same or is in root
if (folder1.title == folder2.title) {
Console.WriteLine("Same: " + folder1.title);
// check for childs
index++;
if (folder1.childs != null) {
foreach (Folder sub in folder1.childs) {
if (folder2.childs != null) {
foreach (Folder sub2 in folder2.childs) {
compareFolders(sub, sub2, newFolders, index);
}
}
}
}
return true;
}
// moment there false, check if root doesn't
if (folder2.childs != null && folder2.childs.Count > 0)
// folder 2 has folder that folder 1 doesn't have
newFolders.AddRange(folder2.childs);
return false;
}
这是最好的工作,但我看到每个文件夹都与更多的文件夹进行比较,然后它应该。
所以我尝试切换到lambda,但无法弄清楚如何做到这一点。这就是我得到的:
private static void compareFolders2(Folder folder1, Folder folder2, List<Folder> newFolders, int index = 0) {
if (folder2.childs != null && folder2.childs.Count > 0) {
if (folder1.childs != null && folder1.childs.Count > 0) {
var similarFolders = folder1.childs.FindAll(f => folder2.childs.Select(f2 => f2.title).ToList().Contains(f.title));
if (similarFolders.Count > 0) {
foreach (Folder folder in similarFolders) {
compareFolders2(folder, folder2.childs.Find(f => f.title == folder.title), newFolders);
}
} else {
newFolders.AddRange(folder2.childs);
}
}
}
}
如果你想尝试一些东西我做了一个简单的C#控制台应用程序,它有一些测试文件夹结构的生成方法,并像示例一样打印 https://gist.github.com/cskiwi/d2e5002af98da6982971
注意:第二个文件夹并不总是包含需要添加的文件夹,在 otherFolder 上增加sublevels
/ maxfolders
以使其更有可能发生
答案 0 :(得分:0)
我想通过这样做来解决它:
private static void compareFolders(Folder folder1, Folder folder2, List<Folder> newFolders) {
if (folder2.childs != null) {
if (folder1.childs != null) {
// check for folder 2 childs not in folder 1
newFolders.AddRange(folder2.childs.FindAll(f => !folder1.childs.Select(f2 => f2.title).ToList().Contains(f.title)));
// for similar folders go one deeper
folder1.childs.FindAll(f => folder2.childs.Select(f2 => f2.title).ToList().Contains(f.title)).ForEach(f1 => compareFolders3(f1, folder2.childs.Find(f2 => f2.title == f1.title), newFolders));
} else {
// folder 1 doesn't have childs so add all of folder2
newFolders.AddRange(folder2.childs);
}
}
}
仍在检查,但看起来喜欢它正在运作