我有与此类似的json:
{
Name: Level 1,
Children: [
{
Name: Level 2,
Children: [
{
Name: Level 3,
Children: [
{
Name: Level 4,
Children: [
{
Name: Level 5,
Children: []
}
]
}
]
}
]
}
]
}
当前的深度级别是5,我正在尝试使用类似于以下的嵌套for循环:
for()
{
for()
{
for()
{
for().....
但是我想知道是否有一种无需使用那么多for循环就可以生成它的方法,因为当前的深度级别是5,但是可能更高。
考虑一下,在以后的某个时间,您决定添加更多级别。使用这种循环方法,您需要修改代码,添加更多的嵌套循环以应对这种情况。因此,可以说这不是一个好的方法。对于这种特定情况,建议您使用类似以下的递归方法:
public void RecursiveMethod(object inputCollection)
{
// process here
if(Check for child collection)
{
RecursiveMethod(inputCollection.Children)
}
// process here no more child exists
}
**注意:**object
在上面的代码中使用适当的类型代替,因为它是JSON,因此您可以使用一种序列化方法来获取集合,但是仍然需要递归方法来处理从序列化器中淘汰的集合
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句