如何在 C# 中简化 TreeView 列表的输出?

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

我得到了一个现有的 Treeview 结构列表,如下所示;

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"
    }
});

ONLY 想要获取 IdText(可能将 Text 字段更改为名为 [=16= 的字段] 也许在这个过程中)对于 parents 和 children 并制作一个新列表。

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();

像上面这样的 class Treeview 的所有可能简化的通用函数是我的实际目标。 任何帮助将不胜感激!

您可以使用递归方法,例如:

public static List<object> GetProps(MyClass item)
        {
            if (item.Children == null) return null;
            var childs = item.Children.Select(c => new
            {
                c.Id,
                Title = c.Text,
                Children = GetProps(c)

            }).ToList();

            return new List<object> { childs };
        }

然后使用:

var modifiedResult = mainList.Select(c => new
            {
                c.Id,
                Title = c.Text,
                Children = GetProps(c)

            }).ToList();

这应该可以正常工作:

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();