c# - 字典使用具有父子层次结构的平面列表进行准备
问题描述
我有一个来自 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;
}
解决方案
推荐阅读
- reactjs - Material-UI ThemeProvider 未将主题传递给组件
- javascript - 将产品配置 JSON 与通用配置 JSON 合并 - 合并其中的数组时出现问题
- java - 图像未在 JavaFX ImageView 中显示
- go - 在 Go API 中创建了 Empty Swagger 规范
- java - 如果测试失败,如何配置测试容器以使数据库容器保持运行?
- prolog - 在 prolog 中创建 if else
- javascript - 在 Angular 上使用传单在 D3 中设置基于地图的投影
- python - 找到矩阵中元素的最小和,使得在加法过程中列应该是连续的
- reactjs - 用大数组反应 useState() 钩子
- java - 使用 JSoup 解析特定的文本值