[英]Loop recursive self join table
我有以下SQL Server表結構,它是一個邏輯樹文件夾結構。
我正在使用Linq to SQL with SQL Server。
我想要做的是循環並在內存上創建文件夾結構,從Root的層次文件夾,所有子項的主要父項。
我試圖用一些foreach循環來做,但我仍然沒有得到它。 我想我必須使用某種遞歸方式。
我嘗試了一些查詢:
var flds = from folders in repo.Folders
join folders2 in repo.Folders on folders.Id equals folders2.idParent
select folders;
我的目標是迭代該文件夾邏輯結構。
如果要將文件夾作為表中給出的層次結構,可以像這樣創建它:
var tableData = repo.Folders.ToList();
var directories = tableData.Select(f => GetPath(f, table));
正如您所問,創建文件夾層次結構的遞歸方法是:
private static string GetPath(Folder f)
{
if (f.IdParent == 0)
{
return f.Name;
}
else
{
var parent = tableData.Find(d => d.Id == f.IdParent);
return GetPath(parent) + "|" + f.Name;
}
}
你會得到這樣的輸出:
它會給你一個完整的文件夾hirarchy,我不知道你想如何使用它。 所以你可以根據需要做一些修改。 希望能幫助到你!
這里我添加代碼來迭代並創建文件夾結構:
foreach (var dir in directories)
{
var folders = dir.Split('|');
var path = string.Empty;
foreach (var folder in folders)
{
path = path + "\\" + folder; // modify the path like '\\' if it is not valid I have not tested
CreateFolder(path); // implement this method for actual creation of folders
}
}
以及創建文件夾的方法:
private static void CreateFolder(string directory)
{
var path = "C:" + directory; // add whenever you want to create structure
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
你可以嘗試這個:
// Get a list of the folders.
// We do this, in order to avoid the performance hit, that Panagiotis
// pointed out correctly in his comment.
var folders = repo.Folders.ToList();
// Get the root folder.
var rootFolder = folders.Where(x=>x.idParent==null).SingleOrDefault();
// Group the folders by their parentId.
var groupedFolders = from folder in folders
where folder.idParent!=null
orderby folder.idParent ascending
group folder by folder.idParent into grp
select new
{
ParentFolderId = grp.Key,
Folders = grp.Select(x=>x)
};
// Print the name of the root folder.
Console.WriteLine("Root Folder", rootFolder.Name);
// Iterate through the groups of folders.
foreach(var grp in groupedFolders)
{
// Get the name of the parent folder for the current group.
string parentFolderName = folders.Where(x=>x.Id==grp.ParentFolderId)
.Single(x=>x.Name);
// Print the name of the parent folder.
Console.WriteLine("Parent Folder", parentFolderName);
// Iterate through the folders of the current group.
foreach(var folder in grp.Folders)
{
Console.WriteLine(folder.Name);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.