I have a table similar to:
did diScheduleLinkedID diScheduleID
8 47 71
9 71 72
10 45 67
11 72 85
12 67 78
14 85 92
where The table is like a linked list diScheduleLinkedID is linked to diScheduleID recursively.
I need to query the table (hopefully in Linq) with an ID say (47) and get back:
47,71,72,85,92
Or with ID 45 and get back:
45,67,78
I tried something similar to: .NET - LINQ AsHierarchy() extension method
however it's not working as expected
EDIT I used the following code from the linked article:
var hierachy = tbllinks.Where(w=>w.diScheduleLinkedID.Equals(pnID)).ToList().AsHierarchy(e => e.diScheduleLinkedID, e => e.diScheduleID);
however it's returning an empty list and I can't see any way to filter for the first ID (say 47) in the linked list?
EDIT 2 Was able to do it using the Extension method:
public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
foreach (T item in source)
{
yield return item;
IEnumerable<T> children = selector(item);
foreach (T child in children.Traverse(selector))
{
yield return child;
}
}
}
and then use:
var result = tblpermit_links.Where(item => item.diScheduleLinkedID == 47)
.Traverse(item => tblpermit_links.Where(parent
=> item.diScheduleID == parent.diScheduleLinkedID));
Not sure of the performance hit though! However I will be able to prefilter the table on another field.
Maybe I should use a CTE?