字典<string,object =“”>准备使用带有父子层次结构的平面列表

时间:2018-11-12 08:50:51

标签: c# json dictionary dynamic hierarchy

我有一个来自SQL存储过程的简单记录列表,其中包含列 ID,键,值,ParentId。

键可能具有任意数量的子级别项,或者键可能具有直接字符串值(如菜单)。因此,我将字典定义为键和对象(对象可以是字符串,也可以是Dictionary<string, object>)。

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

问题在于它具有n个层次结构。因此,在每次递归调用中,我可能都需要像yield和return这样的东西,就像在Enumerable情况下一样,但是在此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;
}

0 个答案:

没有答案