从平面列表创建递归对象

本文关键字:递归 对象 创建 列表 平面 | 更新日期: 2023-09-27 18:09:04

如下图所示:

        List<MenuItem> menuItems = new List<MenuItem>();
        menuItems.Add(new MenuItem() { SiteMenuId = 1, ParentId = null, MenuName = "Menu", Url = null, SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 2, ParentId = 1, MenuName = "aaa", Url = "aaa", SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 3, ParentId = 1, MenuName = "bbb", Url = null, SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 4, ParentId = 3, MenuName = "ccc", Url = "ccc", SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 5, ParentId = 3, MenuName = "ddd", Url = "ddd", SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 6, ParentId = 1, MenuName = "eee", Url = "eee", SiteId = 1 });

是否可以将此数据结构转换为可以序列化为以下json的格式:

{
    "Menu": {
        "aaa": "aaa",
        "bbb": {
            "ccc": "ccc",
            "ddd": "ddd"
        },
        "eee": "eee"
    }
}

如果答案是肯定的,我该怎么做呢?

从平面列表创建递归对象

你可以考虑使用Json.NET。

Json。. NET将任何IDictionary序列化为JSON键/值对对象-但转换为Dictionary<string, object>然后序列化将是有问题的,因为。NET字典是无序的,并且您(可能)希望在序列化为JSON时保留 MenuItem对象的相对顺序。因此,使用LINQ到JSON手动转换为JObject对象树是有意义的,因为JSON。. NET保留对象属性的顺序。

你可以这样做:

    public static string CreateJsonFromMenuItems(IList<MenuItem> menuItems)
    {
        return new JObject
        (
            menuItems.ToTree(
                m => (int?)m.SiteMenuId,
                m => m.ParentId, m => new JProperty(m.MenuName, m.Url),
                (parent, child) =>
                {
                    if (parent.Value == null || parent.Value.Type == JTokenType.Null)
                        parent.Value = new JObject();
                    else if (parent.Value.Type != JTokenType.Object)
                        throw new InvalidOperationException("MenuItem has both URL and children");
                    child.MoveTo((JObject)parent.Value);
                })
        ).ToString();
    }

(注意,如果MenuItem同时具有非空Url和子集合,则该方法会抛出异常)

它使用以下扩展方法:

public static class JsonExtensions
{
    public static void MoveTo(this JToken token, JObject newParent)
    {
        if (newParent == null)
            throw new ArgumentNullException();
        var toMove = token.AncestorsAndSelf().OfType<JProperty>().First(); // Throws an exception if no parent property found.
        if (toMove.Parent != null)
            toMove.Remove();
        newParent.Add(toMove);
    }
}
public static class RecursiveEnumerableExtensions
{
    static bool ContainsNonNullKey<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        return key == null ? false : dictionary.ContainsKey(key); // Dictionary<int?, X> throws on ContainsKey(null)
    }
    public static IEnumerable<TResult> ToTree<TInput, TKey, TResult>(
        this IEnumerable<TInput> collection,
        Func<TInput, TKey> idSelector,
        Func<TInput, TKey> parentIdSelector,
        Func<TInput, TResult> nodeSelector,
        Action<TResult, TResult> addMethod)
    {
        if (collection == null || idSelector == null || parentIdSelector == null || nodeSelector == null || addMethod == null)
            throw new ArgumentNullException();
        var list = collection.ToList(); // Prevent multiple enumerations of the incoming enumerable.
        var dict = list.ToDictionary(i => idSelector(i), i => nodeSelector(i));
        foreach (var input in list.Where(i => dict.ContainsNonNullKey(parentIdSelector(i))))
        {
            addMethod(dict[parentIdSelector(input)], dict[idSelector(input)]);
        }
        return list.Where(i => !dict.ContainsNonNullKey(parentIdSelector(i))).Select(i => dict[idSelector(i)]);
    }
}

工作小提琴。

您可以尝试创建一个这样的类

public class MenuItemTr
{
 public MenuItemTr
 {
    this.MenuItems= new List <MenuItem>
 }
public int SiteMenuId {get; set;}
public int ParentId {get; set;}
public string MenuName {get; set;}
public string Url {get; set;}
public int SiteId {get; set;}
public List <MenuItemTr> MenuItems {get; set;}
}

,然后解析为树

var MenuItem = menuItems.GenerateTree(c => c.SiteMenuId, c => c.ParentId);

和使用这个解决方案从这个线程Nice &将List of items转换为Tree的通用方法

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 => parent_id_selector(c).Equals(root_id)))
        {
            yield return new TreeItem<T>
            {
                Item = c,
                Children = collection.GenerateTree(id_selector, parent_id_selector, id_selector(c))
            };
        }
    }
}