通常我们将平面列表转换为分层列表,但在我的情况下,我想将分层列表转换为平面列表。
我有一个分层list<T>
,我希望将此分层列表转换为平面list<T>
类。
我们说我有一个下面的分层列表
Parent1
--- Child1 ,F1
----Child2, F2
----Child2, F3
Parent2
----Child2,F2
----Child4,F6
Parent3
--- Child1 ,F1
我需要输出如下:
Parent1, Child1,F1
Parent1, Child2,F2
Parent1, Child2,F3
Parent2,Child2,F2
Parent2,Child4, F6
Parent3, Child1,F1
答案 0 :(得分:0)
它可能不是最优化的解决方案(我认为它可以进一步减少,我有一个更简洁的版本 - 但这种形式是我最常用的)
这就是我一直在使用的
public static IEnumerable<T> FlattenHierarchy<T>(this T node,
Func<T, IEnumerable<T>> getChildEnumerator)
{
yield return node;
if (getChildEnumerator(node) != null)
{
foreach (var child in getChildEnumerator(node))
{
foreach (var childOrDescendant
in child.FlattenHierarchy(getChildEnumerator))
{
yield return childOrDescendant;
}
}
}
}
你可以像
一样使用它folder.FlattenHierarchy(x => x.SubFolders)
答案 1 :(得分:0)
最后我找到了解决方案:
public class RNode
{
public string Id;
public long ID;
public string name;
public string subTitle;
public IList<RNode> children;
}
public class FlatObj //For Data format
{
public long Id;
public long ParentId;
public long Position;
public string name;
public string subTitle;
}
List<FlatObj> GlobalFlatObj = new List<FlatObj>();
List<long> ParentIdList = new List<long>();
long CurrentParentId=0;
long CurrentPosition = 0;
public List<FlatObj> FlatData(IList<RNode> HData) //Converting Heirarchical to Flat
{
foreach (RNode node in HData)
{
FlatObj ObjFlatObj = new FlatObj();
ObjFlatObj.Id = node.ID;
ObjFlatObj.name = node.name;
ObjFlatObj.ParentId = CurrentParentId;
ObjFlatObj.Position = CurrentPosition;
GlobalFlatObj.Add(ObjFlatObj);
if (node.children.Count > 0)
{
CurrentParentId = node.ID;
ParentIdList.Add(node.ID);
FlatData(node.children);
}
CurrentPosition++;
}
if (ParentIdList.Count > 0)
{
ParentIdList.RemoveAt(ParentIdList.Count - 1);
if (ParentIdList.Count > 0)
CurrentParentId = ParentIdList[ParentIdList.Count - 1];
CurrentPosition = 0;
}
return GlobalFlatObj;
}
public dynamic Test(List<RNode> EmployeeHierarchy)
{
var HierarchyResult = FlatData(EmployeeHierarchy); //Calling
return Ok(HierarchyResult);
}
输入:
[
{
"$id": "1",
"ID": 1,
"name": "root",
"subTitle": "root",
"children": [
{
"$id": "2",
"ID": 2,
"name": "child 1",
"subTitle": "child 1",
"children": [
{
"$id": "3",
"ID": 5,
"name": "grandchild",
"subTitle": "grandchild",
"children": []
}]
},
{
"$id": "4",
"ID": 3,
"name": "child 2",
"subTitle": "child 2",
"children": []
},
{
"$id": "5",
"ID": 4,
"name": "child 3",
"subTitle": "child 3",
"children": []
}
]
}
]
输出:
[
{
"$id": "1",
"Id": 1,
"ParentId": 0,
"Position": 0,
"name": "root",
"subTitle": null
},
{
"$id": "2",
"Id": 2,
"ParentId": 1,
"Position": 0,
"name": "child 1",
"subTitle": null
},
{
"$id": "3",
"Id": 5,
"ParentId": 2,
"Position": 0,
"name": "grandchild",
"subTitle": null
},
{
"$id": "4",
"Id": 3,
"ParentId": 1,
"Position": 1,
"name": "child 2",
"subTitle": null
},
{
"$id": "5",
"Id": 4,
"ParentId": 1,
"Position": 2,
"name": "child 3",
"subTitle": null
}
]