如何将目录结构放入字典中 [英] How to put the directory structure int a a dictionary

查看:98
本文介绍了如何将目录结构放入字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在c中有一个父文件夹测试:\

我需要检查测试文件夹中有多少子文件夹并将它们放入不同级别的字典中



文件夹结构如



test

test_sub1

test_sub1_sub11 < br $> b $ b test_sub2

test_sub2_sub11



Suppose I have a parent folder test in my c:\
I need to check how many sub folders are present in test folder and put them into dictionary of different levels

Folder Structure Like

test
test_sub1
test_sub1_sub11
test_sub2
test_sub2_sub11

Dictionary<Key,Dictionary> dict=Dictionary<Key,Dictionary>();



第一个子文件夹它将是


for first sub folder it will be

Dictionary<test,Dictionary<test_sub1,Dictionary<test_sub1_sub11,Value>>>



和第二个以及


And for second as well

推荐答案

正式地说,你需要的是一棵n-ary树。嵌套字典会很麻烦且不必要,在c#中你可以做类似下面的事情



Formally, what you need is a n-ary tree. Nesting dictionaries would be messy and unnecessary, in c# you can do something like the following

public class DirectoryThing
{
    public Whatever PropertyOfDirectoryIWantToKeep {get; set;}
    public List<subdirectorythings> {get; private set}
}</subdirectorythings>



随着正确的命名:)等以及你想要输入/输出信息的任何方法/索引器的添加。编写一个转换器来处理.net框架的 DirectoryInfo 类应该很容易。在某些情况下,您甚至可能只想使用 DirectoryInfo 类型。例如,如果你只是计算子目录,你可以实例化根目录的'code> DirectoryInfo 类,使用它的 GetDirectories [ ^ ]方法获取子节点并递归遍历整个树,保持子目录数的运行总计,直到遍历树。


With proper naming :) etc and the addition of any methods/indexers you want to get infotmation in/out. It should be pretty easy to write a converter to work with the .net framework''s DirectoryInfo class. In some circumstances you might even just want to use the DirectoryInfo type. For example if you are just counting subdirectories you can instantiate the root directory''s DirectoryInfo class, use its GetDirectories[^] method to get the children and recursively traverse the whole tree, keeping a running total of the number of subdirectories until the tree is traversed.


这篇关于如何将目录结构放入字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆