There are a TON of examples online, yet I can't find one that addresses what I need, and I'm just not really getting the nuances of recursion. I have an application user table that has a "ParentId" column. I have to start with one user's Id and query the database to find all users whose ParentId is that user's Id, then all users whose ParentId is one of the children's Id, and so on, until I have a flat list of all child Ids of a certain user. No nesting objects or keeping track of hierarchy other than getting all descendant users of a given user. I tried this...
private List<int> GetChildIdsRecursive(int parentId) { var childIds = new List<int>(); return _dbContext.ApplicationUser .Where(r => r.ParentId.HasValue && r.ParentId.Value == parentId) .Select(r => childIds.AddRange(GetChildIdsRecursive(r.Id))); }
But I get this error: Error CS0411 The type arguments for method 'Queryable.Select<TSource, TResult>(IQueryable<TSource>, Expression<Func<TSource, TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
I know how many levels it goes, and so I could brute-force this, but the levels might change in the future. I'd much rather have a scalable solution. I just need to take a single Id, and find all child objects with a matching ParentId, recursively.
This article seemed to be close to what I need, but I don't need or want to create a child collection for each user object and assign the child objects to that collection - I just need the collection of Ids: