首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在c#中将对象的平面列表转换为嵌套的对象列表

在C#中,将对象的平面列表转换为嵌套的对象列表可以通过使用LINQ查询和递归来实现。下面是一个示例代码:

代码语言:txt
复制
using System;
using System.Collections.Generic;
using System.Linq;

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public List<Category> Children { get; set; }
}

public class Program
{
    public static void Main()
    {
        List<Category> categories = new List<Category>
        {
            new Category { Id = 1, Name = "Category 1", ParentId = null },
            new Category { Id = 2, Name = "Category 2", ParentId = null },
            new Category { Id = 3, Name = "Category 1.1", ParentId = 1 },
            new Category { Id = 4, Name = "Category 1.2", ParentId = 1 },
            new Category { Id = 5, Name = "Category 2.1", ParentId = 2 },
            new Category { Id = 6, Name = "Category 2.2", ParentId = 2 },
            new Category { Id = 7, Name = "Category 1.1.1", ParentId = 3 },
            new Category { Id = 8, Name = "Category 1.1.2", ParentId = 3 }
        };

        List<Category> nestedCategories = GetNestedCategories(categories, null);

        foreach (var category in nestedCategories)
        {
            PrintCategory(category);
        }
    }

    public static List<Category> GetNestedCategories(List<Category> categories, int? parentId)
    {
        return categories
            .Where(c => c.ParentId == parentId)
            .Select(c => new Category
            {
                Id = c.Id,
                Name = c.Name,
                ParentId = c.ParentId,
                Children = GetNestedCategories(categories, c.Id)
            })
            .ToList();
    }

    public static void PrintCategory(Category category, string indent = "")
    {
        Console.WriteLine(indent + category.Name);

        if (category.Children != null)
        {
            foreach (var child in category.Children)
            {
                PrintCategory(child, indent + "  ");
            }
        }
    }
}

这个示例代码中,我们定义了一个Category类,包含了IdNameParentIdChildren属性。Id表示分类的唯一标识,Name表示分类的名称,ParentId表示父分类的Id,Children表示子分类列表。

GetNestedCategories方法中,我们使用LINQ查询来筛选出指定父分类Id的子分类,并通过递归调用GetNestedCategories方法来获取子分类的子分类,以此实现将平面列表转换为嵌套的对象列表。

Main方法中,我们创建了一个示例的分类列表,并调用GetNestedCategories方法来获取嵌套的对象列表。然后,我们通过PrintCategory方法递归打印出所有分类及其子分类的层级结构。

这个示例代码中没有涉及到具体的云计算相关内容,因此无法提供腾讯云相关产品和产品介绍链接地址。但是,你可以根据实际需求将这个示例代码应用到云计算领域的具体场景中,例如处理云端的分类数据。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券