c# - 将数组转换为 POCO 对象
问题描述
我无法将以下字符串数组转换为 POCO 对象。鉴于以下情况:
string files = [
"./Folder/file.ext",
"./Folder/file2.ext",
"./Folder/file3.ext",
"./Folder/nestedfolder/file.ext",
"./Folder2/file1.ext",
"./Folder2/file2.ext",
"./file1.ext",
"./file2.ext",
"./file3.ext",
];
我想将其转换为:
public class HierarchicalSource{
public List<HierarchicalSource> Children = new List <HierarchicalSource> ();
public bool folder { get; set; }
public string FullPath;
public HierarchicalSourceSource(string path) {
this.FullPath = path;
}
}
其中 HierarchicalSource 是根,并且有一个子列表
更新:
我最终将列表更改为字典。必须有更有效的方法来做到这一点,但我做了如下:
string fileList = files.Select(x => x.Remove(0, 2)).ToArray();
var root = new HierarchicalSource("root");
foreach(var f in fileList){
var current = root;
string[] splitFile = f.Split('/');
foreach(var s in splitFile){
if(!current.Children.ContainsKey(s)){
current.Children.Add(s, new List<HierarchicalSource>{ new HierarchicalSource(s) });
}
current = current.Children[s].Last();
}
}
POCO:
public class HierarchicalSource{
public string name;
public Dictionary<string, List<HierarchicalSource>> Children = new Dictionary<string, List<HierarchicalSource>>();
public HierarchicalSource(string name){
this.name = name;
}
}
解决方案
如果我理解正确,这需要遍历数组,但它允许您解析数组中的每个项目,以便生成 HierarchicalNode 对象的值。
var node = new HierarchicalSource();
foreach(var str in files)
{
var pathParts = str.Split('/').ToList();
node.Children.Add(new HierarchicalNode()
{
FullPath = str,
Folder = pathParts[1] // you may need to do some debugging to see what the results for pathParts are instead of just [#]
});
}
由于FullPath
HierarchicalNode 中的成员是公共的,因此您可以设置该值而无需通过任何构造函数。
// using the above code for reference
node.FullPath = whateverThePathYouNeedIs;
还要更新类中的该属性以使用 getter 和 setter
public string FullPath { get; set; }
推荐阅读
- google-sheets - 当单元格相等时执行数学运算
- python - 如何让我的图像(矩形)与我随机生成的圆圈碰撞以结束游戏?
- javascript - 如何在 json 中使用 mustache 和单个实体呈现 html 块
- python - 查找一系列行并搜索匹配的列参数
- spring-kafka - @Header 和 Spring Stream 函数式编程模型
- c++ - 初始化结构数组 - C++
- javascript - 使用 javascript 在正文中查找乱码
- javascript - Angular FxFlex Layout MediaOberver - 根据给定的 div 计算活动宽度?
- gradle - 如何在 gradle 任务中从依赖 jar 中引用资源文件?
- aws-lambda - AWS Lambda 函数短暂监听来自 Thing 的 MQTT 消息