using System.Collections;
using System.Collections.Generic;
public static void Main()
var list = new List<S>() {
new S() { Id = 1, Name = "Mobile", ParentId = null} ,
new S() { Id = 2, Name = "Transport", ParentId = 1} ,
new S() { Id = 3, Name = "Payment", ParentId = 2} ,
new S() { Id = 4, Name = "X", ParentId = null} ,
new S() { Id = 5, Name = "Y", ParentId = 4} ,
new S() { Id = 6, Name = "Z", ParentId = 5} ,
new S() { Id = 7, Name = "ZZZ", ParentId = null}
List<string> Result = new List<string>();
getChilderen(0,list,Result,"");
public static void getChilderen (int parentId,List<S> children, List<string> Result,string name) {
lst = children.Where(c=>c.ParentId == null).ToList();
Result.Add(name==""?item.Name : name + "-" + item.Name);
getChilderen(item.Id,children,Result,name + "-" +item.Name);
lst = children.Where(c=>c.ParentId == parentId).ToList();
Result.Add(name==""?lst.ElementAt(0).Name : name + "-" + lst.ElementAt(0).Name);
getChilderen(lst.ElementAt(0).Id,children,Result,name + "-" +lst.ElementAt(0).Name);
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }