首页 > 解决方案 > 将数组转换为 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;
    }
}

标签: c#asp.netpoco

解决方案


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

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

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

还要更新类中的该属性以使用 getter 和 setter

public string FullPath { get; set; } 

推荐阅读