在C#中,将对象的平面列表转换为嵌套的对象列表可以通过使用LINQ查询和递归来实现。下面是一个示例代码:
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
类,包含了Id
、Name
、ParentId
和Children
属性。Id
表示分类的唯一标识,Name
表示分类的名称,ParentId
表示父分类的Id,Children
表示子分类列表。
在GetNestedCategories
方法中,我们使用LINQ查询来筛选出指定父分类Id的子分类,并通过递归调用GetNestedCategories
方法来获取子分类的子分类,以此实现将平面列表转换为嵌套的对象列表。
在Main
方法中,我们创建了一个示例的分类列表,并调用GetNestedCategories
方法来获取嵌套的对象列表。然后,我们通过PrintCategory
方法递归打印出所有分类及其子分类的层级结构。
这个示例代码中没有涉及到具体的云计算相关内容,因此无法提供腾讯云相关产品和产品介绍链接地址。但是,你可以根据实际需求将这个示例代码应用到云计算领域的具体场景中,例如处理云端的分类数据。
领取专属 10元无门槛券
手把手带您无忧上云