gpt4 book ai didi

c# - 将项目列表转换为树的通用方法

转载 作者:IT王子 更新时间:2023-10-29 04:03:24 24 4
gpt4 key购买 nike

我有类别列表:

╔════╦═════════════╦═════════════╗
║ Id ║ Name ║ Parent_id ║
╠════╬═════════════╬═════════════╣
║ 1 ║ Sports ║ 0 ║
║ 2 ║ Balls ║ 1 ║
║ 3 ║ Shoes ║ 1 ║
║ 4 ║ Electronics ║ 0 ║
║ 5 ║ Cameras ║ 4 ║
║ 6 ║ Lenses ║ 5 ║
║ 7 ║ Tripod ║ 5 ║
║ 8 ║ Computers ║ 4 ║
║ 9 ║ Laptops ║ 8 ║
║ 10 ║ Empty ║ 0 ║
║ -1 ║ Broken ║ 999 ║
╚════╩═════════════╩═════════════╝

每个类别都有一个父级。当 parent 为 0 - 这意味着它是根类别。

将其转换为如下所示的树结构的最佳方法是什么?

Sport
├ Balls
└ Shoes

Electronics
├ Cameras
│ ├ Lenses
│ └ Tripod

└ Computers
└ Laptops

Empty

换句话说——如何从这个结构中获取数据:

class category
{
public int Id;
public int ParentId;
public string Name;
}

进入这个:

class category
{
public int Id;
public int ParentId;
public string Name;

public List<Category> Subcategories;
}

以通用方式? //通用意味着不仅仅针对提到的类。

你有什么聪明的点子吗? ;)


数据:

var categories = new List<category>() {
new category(1, "Sport", 0),
new category(2, "Balls", 1),
new category(3, "Shoes", 1),
new category(4, "Electronics", 0),
new category(5, "Cameras", 4),
new category(6, "Lenses", 5),
new category(7, "Tripod", 5),
new category(8, "Computers", 4),
new category(9, "Laptops", 8),
new category(10, "Empty", 0),
new category(-1, "Broken", 999),
};

最佳答案

如果你想拥有通用方法,你将需要一个额外的类:

public class TreeItem<T>
{
public T Item { get; set; }
public IEnumerable<TreeItem<T>> Children { get; set; }
}

然后将它与这个助手一起使用:

internal static class GenericHelpers
{
/// <summary>
/// Generates tree of items from item list
/// </summary>
///
/// <typeparam name="T">Type of item in collection</typeparam>
/// <typeparam name="K">Type of parent_id</typeparam>
///
/// <param name="collection">Collection of items</param>
/// <param name="id_selector">Function extracting item's id</param>
/// <param name="parent_id_selector">Function extracting item's parent_id</param>
/// <param name="root_id">Root element id</param>
///
/// <returns>Tree of items</returns>
public static IEnumerable<TreeItem<T>> GenerateTree<T, K>(
this IEnumerable<T> collection,
Func<T, K> id_selector,
Func<T, K> parent_id_selector,
K root_id = default(K))
{
foreach (var c in collection.Where(c => EqualityComparer<K>.Default.Equals(parent_id_selector(c), root_id)))
{
yield return new TreeItem<T>
{
Item = c,
Children = collection.GenerateTree(id_selector, parent_id_selector, id_selector(c))
};
}
}
}

用法:

var root = categories.GenerateTree(c => c.Id, c => c.ParentId);

测试:

static void Test(IEnumerable<TreeItem<category>> categories, int deep = 0)
{
foreach (var c in categories)
{
Console.WriteLine(new String('\t', deep) + c.Item.Name);
Test(c.Children, deep + 1);
}
}
// ...
Test(root);

输出

Sport
Balls
Shoes
Electronics
Cameras
Lenses
Tripod
Computers
Laptops
Empty

关于c# - 将项目列表转换为树的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19648166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com