Search code examples
c#recursionanonymous-typestreelist

How to simplify the output of a TreeView list in C#?


I got an existing Treeview structure List as below;

var mainList = new List<MyClass>();
mainList.AddRange(new List<MyClass>
{
    new MyClass
    {
        Id = 1,
        Text = "Node1",
        UnwantedProp1 = "somevalue",
        UnwantedProp2 = "somevalue",
        UnwantedProp3 = "somevalue",
        Children = new List<MyClass>
        {
            new MyClass
            {
                Id = 11,
                Text = "Node11",
                UnwantedProp1 = "somevalue",
                UnwantedProp2 = "somevalue",
                UnwantedProp3 = "somevalue",
                Children = new List<MyClass>
                {
                    new MyClass
                    {
                        Id = 111,
                        Text = "Node111",
                        UnwantedProp1 = "somevalue",
                        UnwantedProp2 = "somevalue",
                        UnwantedProp3 = "somevalue"
                    }
                }
            },
            new MyClass
            {
                Id = 12,
                Text = "Node12",
                UnwantedProp1 = "somevalue",
                UnwantedProp2 = "somevalue",
                UnwantedProp3 = "somevalue"
            }
        }
    },
    new MyClass
    {
        Id = 2,
        Text = "Node2",
        UnwantedProp1 = "somevalue",
        UnwantedProp2 = "somevalue",
        UnwantedProp3 = "somevalue"
    }
});

I ONLY want to take the Id and Text (possibly change the Text field into a field called Title perhaps during the process) for both parents and children and make a new list.

var modifiedResult = mainList.Select(c => new
    {
        c.Id,
        Title = c.Text,
        Children = c.Children.Select(p => new
        {
            p.Id,
            Title = p.Text,
            Children = p.Children.Select(j => .... ... )//<-- How do we Recursive this?
        }).ToList(),
})
.ToList();

A common function for all possible simplification of a class Treeview like this one above is my actual goal. Any help would be highly appreciated!


Solution

  • This should work fine:

    Func<MyClass, dynamic> convertor = null;
    convertor = m => new { Id = m.Id, Title = m.Text, Children = (m.Children != null ? m.Children.Select(convertor) : null) };
    var newMainList2 = mainList.Select(convertor).ToList();