栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

生成层次结构的C#算法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

生成层次结构的C#算法

非常感谢Jon和mquander-你们给了我足够的信息,可以帮助我以适当的通用方式解决此问题。这是我的解决方案,一种将对象转换为层次结构形式的通用扩展方法:

public static IEnumerable<Node<T>> Hierarchize<T, TKey, TOrderKey>(    this IEnumerable<T> elements,     TKey topMostKey,     Func<T, TKey> keySelector,     Func<T, TKey> parentKeySelector,     Func<T, TOrderKey> orderingKeySelector){    var families = elements.ToLookup(parentKeySelector);    var childrenFetcher = default(Func<TKey, IEnumerable<Node<T>>>);    childrenFetcher = parentId => families[parentId]        .OrderBy(orderingKeySelector)        .Select(x => new Node<T>(x, childrenFetcher(keySelector(x))));    return childrenFetcher(topMostKey);}

利用此小节点类:

public class Node<T>{    public T Value { get; private set; }    public IList<Node<T>> Children { get; private set; }    public Node(T value, IEnumerable<Node<T>> children)    {        this.Value = value;        this.Children = new List<Node<T>>(children);    }}

它足够通用,可以解决各种问题,包括我的文本文件问题。好漂亮!

*更新*:这是您的使用方式:

// Given some example data:var items = new[] {   new Foo()    {      Id = 1,      ParentId = -1, // Indicates no parent      Position = 0   },   new Foo()    {      Id = 2,      ParentId = 1,      Position = 0   },   new Foo()    {      Id = 3,      ParentId = 1,      Position = 1   }};// Turn it into a hierarchy! // We'll get back a list of Node<T> containing the root nodes.// Each node will have a list of child nodes.var hierarchy = items.Hierarchize(    -1, // The "root level" key. We're using -1 to indicate root level.    f => f.Id, // The ID property on your object    f => f.ParentId, // The property on your object that points to its parent    f => f.Position, // The property on your object that specifies the order within its parent    );


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660536.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号