I have one list of records having parent child relation. As per the below example if we start from 5 which is having lowest sort order the squence will be 5,7,4,3,1,6,2
Now if I pass 3 I want parentId list that is 4,7,5 and childId list that is 1,6,2 I am able to achieve this by recursive function as per below method. Can somone help me to achive this by linq query rather than recursive method.
public class ParentChildClass
{
public int Id { get; set; }
public int? ChildId { get; set; }
public int SortOrder { get; set; }
}
List<ParentChildClass> parentChildList = new List<ParentChildClass>();
public void CreateParentChildList()
{
parentChildList.Add(new ParentChildClass() { Id = 1, ChildId = 6 , SortOrder = 100});
parentChildList.Add(new ParentChildClass() { Id = 2, ChildId = null, SortOrder = 100 });
parentChildList.Add(new ParentChildClass() { Id = 3, ChildId = 1 , SortOrder = 100 });
parentChildList.Add(new ParentChildClass() { Id = 4, ChildId = 3 , SortOrder = 100 });
parentChildList.Add(new ParentChildClass() { Id = 5, ChildId = 7 , SortOrder = 10 });
parentChildList.Add(new ParentChildClass() { Id = 6, ChildId = 2 , SortOrder = 100 });
parentChildList.Add(new ParentChildClass() { Id = 7, ChildId = 4 , SortOrder = 100 });
}
public List<int> GetRecursiveParentIds (int parentId,List<int> parentIds)
{
CreateParentChildList();
var parent = parentChildList.FirstOrDefault(i => i.ChildId == parentId);
if (parent != null)
{
if (parentIds == null || !parentIds.Any())
{
parentIds = new List<int>();
}
if (parent.ChildId != null)
{
parentIds.Add((int)parent.Id);
GetRecursiveParentIds((int)parent.Id, parentIds);
}
}
return parentIds;
}
public List<int> GetRecursiveChildIds(int childId, List<int> childIds)
{
CreateParentChildList();
var child = parentChildList.FirstOrDefault(i => i.Id == childId);
if (child != null)
{
if (childIds == null || !childIds.Any())
{
childIds = new List<int>();
}
if (child.ChildId != null)
{
childIds.Add((int)child.ChildId);
GetRecursiveChildIds((int)child.ChildId, childIds);
}
}
return childIds;
}
Thanks