简体   繁体   English

从C#中的列表转换为html(嵌套ul li)

[英]Convert to html (nested ul li) from list in C#

I have a list like the following (sample): 我有一个如下列表(示例):

从C#中的列表转换为html(嵌套ul li)

But this list is just a sample for logic. 但这只是逻辑示例。 The list should be dynamic. 该列表应该是动态的。 List field may have more than 3 and The list can have a collection of the child (data format like json) 列表字段可能有3个以上,并且列表可以包含子项的集合(数据格式,例如json)

I want to convert nested ul-li html tags. 我想转换嵌套的ul-li html标签。 I think, I can do that with reflection like following. 我想,我可以像下面这样思考。 But I am using to the reflection first time. 但是我第一次习惯于反思。 My code is like following for now. 我的代码现在如下。 What should I do for that? 我该怎么办?

    public static string ConvertToHtml<T>(IEnumerable<T> list) where T : class
    {
        StringBuilder html = new StringBuilder();
        foreach (var item in list)
        {
            Type itemType = item.GetType();
            if (itemType.IsClass)
            {
                FieldInfo[] fieldInfo = itemType.GetFields(BindingFlags.Public | BindingFlags.Instance); // Field?
                if (fieldInfo.Any())
                {
                    foreach (var field in fieldInfo)
                    {
                        var name = field.Name;
                        var value = field.GetValue(item);
                    }
                }
                PropertyInfo[] propertyInfo = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance); // Property?
                if (propertyInfo.Any())
                {
                    foreach (var property in propertyInfo)
                    {
                        var name = property.Name;
                        var value = property.GetValue(item);
                    }
                }

            }
        }
        return string.Empty;
    }

Most likely you have chosen a wrong approach to do the task. 您很可能选择了错误的方法来完成任务。 The reflection is typically used for querying the runtime code structures like types, their fields, properties and methods. 反射通常用于查询运行时代码结构,例如类型,其字段,属性和方法。 The most common use case for that is creating a method for serialization/deserialization of arbitrary types. 最常见的用例是创建一种对任意类型进行序列化/反序列化的方法。

In your case it does not look like the arbitrary structure - you have quite strict data structure even though it is supports infinite (conceptually) nested levels (like JSON). 在您的情况下,它看起来不像任意结构-尽管它支持无限(概念上)嵌套级别(如JSON),但您具有相当严格的数据结构。 In other words, you have "tree" https://en.wikipedia.org/wiki/Tree_(data_structure) . 换句话说,您拥有“树” https://en.wikipedia.org/wiki/Tree_(data_structure)

To traverse it several algorithms exists: https://en.wikipedia.org/wiki/Tree_traversal and of course for most of them you can easy find the sample implementation: Implementing Depth First Search into C# using List and Stack But the problem is a bit tricky than you can expect as you first need to understand the concept. 要遍历它,可以使用以下几种算法: https : //en.wikipedia.org/wiki/Tree_traversal ,当然,对于大多数算法,您可以轻松地找到示例实现: 使用列表和堆栈在C#中实现深度优先搜索但是问题是首先需要了解这个概念,这比您预期的要棘手。

The tree traversal algorithms are typically recursive. 树遍历算法通常是递归的。 So in order to do it right you have to get into this concept as well. 因此,为了正确执行此操作,您也必须进入这个概念。

After that the code for building the list is quite simple: 之后,用于构建列表的代码非常简单:

public class Node {
    string Name { get; set; }
    IList<Node> Subnodes { get; private set; }
}

private void BuildList(Node node, StringBuilder sb) {
    sb.Append("<ul>");
    foreach (var n in node.Subnodes) {
        sb.Append("<li>" + n.Name);
        BuildList(n, sb);
        sb.Append("</li>");
    }
    sb.Append("</ul>");
}

public string BiuldList(Node root) {
    var sb = new StringBuilder();
    BuildList(root, sb);
    return sb.ToString();
}

EDIT 编辑

Using the given code it would generate empty <ul></ul> tags inside the <li></li> items who don't have children. 使用给定的代码,它会在没有孩子的<li></li>项内生成空的<ul></ul>标记。 So I did a slightly change adding a condition to only create the sub list when there are children. 因此,我做了一点改动,添加了一个条件,仅在有孩子时才创建子列表。

Code: 码:

private void BuildList(Node node, StringBuilder sb) {
       if(node.Subnodes.Count > 0){
            sb.Append("<ul>");
            foreach (var n in node.Subnodes) {
                sb.Append("<li>" + n.Name);
                BuildList(n, sb);
                sb.Append("</li>");
            }
            sb.Append("</ul>");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM