C
C#3w ago
Alex Frost

Issue sending parent Id through recursive function

I have a function that goes through provided nested enumerable with varying depth. It returns element that pass the given condition. I'm having issue with child elements to have I'd of the parent. For that, I am trying to pass Id of found valid element through the preceding recursion but it's having 0 for all the elements.
internal static class FilterService
{
internal static IEnumerable<TableElement> FilterStructureElements(
IEnumerable<PdfStructureElement> elements,
Func<PdfStructureElement, bool> predicate,
int parentId = 0)
{
foreach (var element in elements)
{
// If the current element passes the predicate, yield it as a TableElement with the current parentId
if (predicate(element))
{
yield return element.ToTableElement(parentId);
parentId = element.Order;
}

// Recursively filter children, passing the current parentId to them
foreach (var child in FilterStructureElements(element.ChildElements, predicate, parentId))
{
yield return child;
}
}
}
}
 
internal static class FilterService
{
internal static IEnumerable<TableElement> FilterStructureElements(
IEnumerable<PdfStructureElement> elements,
Func<PdfStructureElement, bool> predicate,
int parentId = 0)
{
foreach (var element in elements)
{
// If the current element passes the predicate, yield it as a TableElement with the current parentId
if (predicate(element))
{
yield return element.ToTableElement(parentId);
parentId = element.Order;
}

// Recursively filter children, passing the current parentId to them
foreach (var child in FilterStructureElements(element.ChildElements, predicate, parentId))
{
yield return child;
}
}
}
}
 
8 Replies
Alex Frost
Alex FrostOP3w ago
Yes trying, thank you for advice
Sehra
Sehra3w ago
parentId is not used after the assignment, you are passing element.Order instead
Alex Frost
Alex FrostOP3w ago
yes sorry, it seems I pasted older code. I did use parentId, but that also gives 0 I've updated the code
Alex Frost
Alex FrostOP3w ago
No description
Sehra
Sehra3w ago
set a breakpoint in the assignment and check what element.Order actually is, maybe it's zero
Alex Frost
Alex FrostOP3w ago
element.Order is also assigned to ID for current element in element.ToTableElement(parentId); and in sample output, you can see the ID which infact is element.Order
Sehra
Sehra3w ago
well, if ToTableElement also sets element.Order to parentId, it would always be zero

Did you find this page helpful?