【问题标题】:Turn array into a POCO object将数组转换为 POCO 对象
【发布时间】:2019-12-17 11:44:57
【问题描述】:

我在将以下字符串数组转换为 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;
    }
}

【问题讨论】:

  • 所以....,向我们展示您的尝试。提示:拆分/ 上的字符串并迭代返回的数组。寻找孩子。如果不存在,添加它。
  • 你认为也许你可以验证你的 c# 代码吗?

标签: c# asp.net poco


【解决方案1】:

如果我理解正确,这需要遍历数组,但它允许您解析数组中的每个项目,以便生成 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 [#]
    });
}

由于 HierarchicalNode 中的 FullPath 成员是公共的,因此您可以设置该值而无需通过任何构造函数。

// using the above code for reference
node.FullPath = whateverThePathYouNeedIs;

同时更新类中的属性以使用 getter 和 setter

public string FullPath { get; set; } 

【讨论】:

  • 谢谢,我相信这个解决方案只处理第一个文件夹而不是子文件夹。 “./Folder/subfolder/subfolder2/file.ext”如何适应这种情况?
  • 在这种情况下,您可以查看该数组 pathParts。它会分解数组中的字符串,然后您只需筛选pathParts 即可获取所有子文件夹。
猜你喜欢
  • 2011-12-31
  • 2021-05-03
  • 2018-12-04
  • 2021-06-16
  • 1970-01-01
  • 2019-07-11
相关资源
最近更新 更多