使用具有父子层次结构的平面列表进行准备,c#,json,dictionary,dynamic,hierarchy"/>

首页 > 解决方案 > 字典使用具有父子层次结构的平面列表进行准备

问题描述

我有一个来自 SQL 存储过程的平面记录列表,其中包含ID、Key、Value、ParentId 列。

一个键可以有任意数量的子级项目,或者一个键可以有一个直接的字符串值(如菜单)。所以我将我的字典定义为键和对象(对象可能是字符串或再次 a Dictionary<string, object>)。

我需要准备对象字典,因为键值是数据库中的动态值,我需要将其转换为 json。所以IEnumerable<objects>是不可能的。所以我正在使用Dictionary<string, object>.

问题是它有 n 个层次结构。因此,在每个递归调用中,我可能需要像在 Enumerable 案例中所做的那样 yield 和 return 之类的东西,但是在这个 Dictionary 上,我需要将子级别添加到其直接父键中。我不确定如何使用字典来处理它。

这是我的代码。我想,我错过了一些东西。

private Dictionary<string, object> headerFooterValues;
private List<S_Get_HeaderFooter_Result> headerFooterResult = default(List<S_Get_HeaderFooter_Result>);

public bool PrepareTree(List<S_Get_HeaderFooter_Result> headerFooters, Dictionary<string, object> childItems, string parentKey = null)
{
    bool status = false;
    Dictionary<string, object> childKeyValuePairs = new Dictionary<string, object>();
    try
    {
        foreach (S_Get_HeaderFooter_Result item in headerFooters)
        {
            /// always check the whole list
            bool hasChildren = headerFooterResult.Any(row => item.EntityTypeId == row.ParentId);

            /// has children object collection
            if (hasChildren)
            {
                if (!string.IsNullOrEmpty(parentKey))
                {
                    childKeyValuePairs = (Dictionary<string, object>)headerFooterValues[parentKey];
                    childKeyValuePairs.Add(item.Key, new Dictionary<string, object>());
                    headerFooterValues[parentKey] = childKeyValuePairs;
                }
                else
                {
                    headerFooterValues.Add(item.Key, new Dictionary<string, object>());
                }
                status = PrepareTree(headerFooterResult.Where(row => item.EntityTypeId == row.ParentId).ToList(), childKeyValuePairs, item.Key);
            }
            /// has no children
            if (!string.IsNullOrEmpty(parentKey)) //if parent key exists prepare child dictionary items
            {
                childKeyValuePairs = (Dictionary<string, object>)headerFooterValues[parentKey];
                childKeyValuePairs.Add(item.Key, item.Value);
            }
            else if (!headerFooterValues.ContainsKey(item.Key)) //else prepare parentroot dictionary items
            {
                headerFooterValues.Add(item.Key, item.Value);
            }
        }
        if (!string.IsNullOrEmpty(parentKey))
        {
            headerFooterValues[parentKey] = childKeyValuePairs;
        }
        status = true;
    }
    catch (Exception)
    {
        status = false;
        throw;
    }

    return status;
}

标签: c#jsondictionarydynamichierarchy

解决方案


推荐阅读