c# - 在 C# 中使用文件路径可视化文件字典的最佳实践
问题描述
我在 C# 中有一个包含 2 个字符串的字典,它代表文件名和文件的路径。我想将这些可视化为一个表单,其中包含文件夹的 TreeView 和实际文件夹的关联文件的 ListView。所以这应该显示字典中的数据,就像文件浏览器一样:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("File1","Folder1\\Folder2");
dict.Add("File2","Folder1\\Folder2\\Folder3");
dict.Add("File3","Folder1");
dict.Add("File4","Folder1\\Folder2");
……
我正在寻找一个好的实现来将其呈现给一个表单:
public MethodBrowserForm(Dictionary<string, string> filesAndFolders)
{
InitializeComponent();
string lastMethodFolder = "";
Dictionary<int, List<string>> folderDictionary = new Dictionary<int, List<string>>();
foreach (var method in filesAndFolders)
{
// Compare Key Values for Folders
if (!lastMethodFolder.Equals(method.Value))
{
// Extract Folder
string[] directories = filesAndFolders.Value.Split(Path.DirectorySeparatorChar);
if (directories.Length > 1 )
// First Level Folders
{
// Implementation for Visualization
}
}
lastMethodFolder = filesAndFolders.Value;
}
}
解决方案
尝试以下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication62
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("File1", "Folder1\\Folder2");
dict.Add("File2", "Folder1\\Folder2\\Folder3");
dict.Add("File3", "Folder1");
dict.Add("File4", "Folder1\\Folder2");
List<KeyValuePair<string, List<string>>> files = dict.Select(x => new KeyValuePair<string, List<string>>(x.Key, x.Value.Split(new char[] {'\\'}).ToList())).ToList();
TreeNode root = new TreeNode();
CreateTree(null, files);
treeView1.ExpandAll();
}
public void CreateTree(TreeNode node, List<KeyValuePair<string, List<string>>> files)
{
var folders = files.GroupBy(x => x.Value.First()).ToList();
foreach (var folder in folders)
{
TreeNode newNode = new TreeNode(folder.Key);
if (node == null)
{
treeView1.Nodes.Add(newNode);
}
else
{
node.Nodes.Add(newNode);
}
List<KeyValuePair<string, List<string>>> child = new List<KeyValuePair<string, List<string>>>();
foreach (KeyValuePair<string, List<string>> file in folder)
{
if (file.Value.Count == 1)
{
newNode.Nodes.Add(file.Key);
}
else
{
KeyValuePair<string, List<string>> newFile = new KeyValuePair<string, List<string>>(file.Key, file.Value.Skip(1).ToList());
child.Add(newFile);
}
}
if (child != null)
{
CreateTree(newNode, child);
}
}
}
}
}
推荐阅读
- grails - 将选定的单选按钮值传递给 groovy 控制器
- ios - Firebase 数据库和检查电话联系人 ios
- amazon-web-services - AWS 负载均衡器 - 更改区域(使用 Terraform)
- react-native - 如何在页面的特定坐标处呈现视图?
- javascript - 未捕获(承诺)DOMException javascript
- php - 创建一个用于安装的 php 脚本
- angular - 在路线之间导航时再次加载数据 - Angular 7
- javascript - 三 JS,.ply 文件的类型有区别吗?
- angular - postMessage 到以角度 *ngFor 创建的 iframe 不起作用
- angularjs - 无法读取未定义堆栈模板的菜单 pixinvent