I’ve been through the same situation and solved using Linq
as follows:
using System.Collections.Generic;
namespace XXX
{
public class TreeviewItem
{
public TreeviewItem()
{
Children = new List<TreeviewItem>();
}
public string Text { get; set; }
public int Value { get; set; }
public int? ValuePai { get; set; }
public bool Checked { get; set; }
public bool Disabled { get; set; }
public bool Collapsed { get; set; }
public List<TreeviewItem> Children { get; set; }
}
}
Methods:
public List<TreeviewItem> ObterListaAninhada(List<TreeviewItem> lstFuncoes)
{
var lstFuncoesAninhadas = lstFuncoes.Where(x => x.ValuePai == 0)
.Select(x => new TreeviewItem
{
Value = x.Value,
ValuePai = x.ValuePai,
Text = x.Text,
Checked = x.Checked,
Collapsed = x.Collapsed,
Disabled = x.Disabled,
Children = ObterFuncoesFilhas(lstFuncoes, x.Value)
}).ToList();
return lstFuncoesAninhadas;
}
private List<TreeviewItem> ObterFuncoesFilhas(List<TreeviewItem> lstFunction, int id)
{
return lstFunction.Where(x => x.ValuePai == id)
.Select(x => new TreeviewItem
{
Value = x.Value,
ValuePai = x.ValuePai,
Text = x.Text,
Checked = x.Checked,
Collapsed = x.Collapsed,
Disabled = x.Disabled,
Children = ObterFuncoesFilhas(lstFunction, x.Value)
}).ToList();
}
Simple example of the result in Json:
{
"text": "Teste",
"value": 305,
"valuePai": 0,
"checked": false,
"disabled": true,
"collapsed": true,
"children": [
{
"text": "Teste.pdf",
"value": 483,
"valuePai": 305,
"checked": false,
"disabled": false,
"collapsed": true,
"children": []
},
{
"text": "Teste.txt",
"value": 487,
"valuePai": 305,
"checked": false,
"disabled": false,
"collapsed": true,
"children": []
}
]
}