This question is taken from Stack Overflow : )..I had taught to myself writing recursive query with LINQ.
Input :
public class InputClass { public int id { get; set; } public string text { get; set; } public string icon { get; set; } public int? parentId { get; set; } } static void Main(string[] args) { var inputList = new List<InputClass>(); inputList.Add(new InputClass() { id = 1, text = "Item #1" }); inputList.Add(new InputClass() { id = 2, text = "Item #2" }); inputList.Add(new InputClass() { id = 3, text = "Item #3" }); inputList.Add(new InputClass() { id = 4, text = "SubItem #1", parentId = 1 }); inputList.Add(new InputClass() { id = 5, text = "SubItem #2", parentId = 1 }); inputList.Add(new InputClass() { id = 6, text = "SubItem #3", parentId = 2 }); inputList.Add(new InputClass() { id = 7, text = "Sub-Sub Item #1", parentId = 4 }); }
Output:
write a linq query to generate all child elements when parent id is passed.
Example : when ParentId is 1 ,then the following output must be produced
ID Name
4 Subitem #1
5 Subitem #2
7 Sub-Sub Item #1
Note : Id 4 & 5 has parent id of 1 and ID 7 has parent id of 4 which inturn points to parent id 1.
Code :
1.First we will write a method to return list of elements that matches the parent id.
Method :
private static List<InputClass> GetAllChildElements(int parentid, List<InputClas>input) { return input.Where(x => x.parentId == parentid).ToList(); }
This method would return 4& 5 when parent id is passed as 1. 2.Next we must check if the returned list has any child elements associated with it. In this case returned list Id 4 has a reference to child element 7. we must again execute the same
query but now the parent id would be returned list Ids.
private static List<InputClass> GetRecursiveList(int p, List<InputClass> inputList)
{
var result = inputList.Where(x => x.parentId == p).ToList();
var temp = new List<InputClass>();
foreach (var inputClass in result)
{
temp.AddRange(GetRecursiveList(inputClass.id, inputList));
}
var t=result.Union(temp);
return t.ToList();
}