# 求一个分组的算法

0

``````string[] list = [
"a1:b1:c1",
"a1:b2:c2:d1:",
"a2:b2:c2:d2"
...
];``````

``````[
{
"name": "a1",
"child": [
{
"name": "b1",
"child": [
{
"name": "c1",
"child": []
}
]
},
{
"name": "b2",
"child": [
{
"name": "c2",
"child": [
{
"name": "d1",
"child": []
},
{
"name": "d2",
"child": []
}
]
}
]
}
]
}
]``````

0
``````[Test]
public void Test1()
{
var dataList = new[] {"a1:b1:c1", "a1:b2:c2:d1:", "a2:b2:c2:d2"};
var root = new List<dynamic>();
var dict = new Dictionary<string, dynamic>();//字典，方便搜索node
foreach (var data in dataList)
{
dynamic parent = null;
foreach (var name in data.Split(':'))
{
dict.TryGetValue(name, out var current);
if (current != null)
{
parent = current;
continue;
}

var node = new {name, child = new List<dynamic>()};
if (parent == null)
{
}
else
{
}

parent = node;
}
}

Console.WriteLine(DefaultJsonSerializer.Instance.SerializeObject(root));
}``````
``[{"name":"a1", "child":[{"name":"b1", "child":[{"name":"c1", "child":[]}]},{"name":"b2", "child":[{"name":"c2", "child":[{"name":"d1", "child":[{"name":"", "child":[]}]},{"name":"d2", "child":[]}]}]}]},{"name":"a2", "child":[]}]``

0
``````lis = [
"a1:b1:c1",
"a1:b2:c2:d1:",
"a2:b2:c2:d2"
]
new_lis =[]
for str in lis:
str_lis = str.split(':')
dic ={}
start_index = 0
def func(dic,start_index):
if start_index==len(str_lis):return
dic['name']= str_lis[start_index]
start_index+=1
dic ['child']={}
func(dic['child'],start_index)
func(dic,start_index)
new_lis.append(dic)
print(new_lis)

``````

@小小咸鱼YwY: 大兄弟，这是啥语法啊。。c#怎么写？

@翩若游龙: python,你只要用递归的思想就可以了,蛮简单的

@翩若游龙:

``````lis = [
"a1:b1:c1",
"a1:b2:c2:d1:",
"a2:b2:c2:d2"
]
new_lis =[]
for str in lis:
str_lis = str.split(':')                 #首先肯定切分
start_index = 0
def func(lis,start_index):         #导入一个空列表
if start_index==len(str_lis):return    #这是为了停掉递归程序,你也可以用其他方法
new_dic ={}     #里面数据填充
new_dic['name'] = str_lis[start_index]
new_dic['child']=[]
start_index += 1
lis.append(new_dic)
func(new_dic['child'], start_index)    #他下一次执行列表是他创建dict里面child里的列表
func(new_lis,start_index)
print(new_lis)``````

0

0

0

0

list.Select(t=>t.Split(":")).Select(t=>new {

name=t[0],

childre=new List{

new {。。。}

}

})

//Modify 不好意思 没注意是字符串，字符串更简单，把第二Select 做字符串格式化一下，再用Aggregate连接一下

您需要登录以后才能回答，未注册用户请先注册