Been looking for a solution for this but haven’t been able to find one so far.
I’m fairly sure its possible with one linq call but having trouble working it out.
I have the following data structure
Id ParentId Name ValidFlag
1 NULL parent 1 1
2 NULL parent 2 1
3 NULL parent 3 0
4 1 child 1 1
5 1 child 2 1
6 2 child 3 1
7 2 child 4 1
8 3 child 5 1
9 3 child 6 1
Now what i want to do is return all valid parents and their children so this case i would return everything except Id = 3 (parent 3).
Is there a simple way to do this with LINQ? Im guessing there is but my LinqIQ is very limited, i know the basics but beyond that i need much help.
Is this a case for ToLookup() or Union or neither?
Update:
To be more specific as I’ve failed to do so, both types of records are in the same table, i want to return all records whether its a parent or child in the 1 query if possible.
Its not as simple as just selecting all records where ValidFlag = 1. The source database is a mess and the only way to get all records is to find the “valid” parents then find all children for the “valid” parents. I know i can just do a simple query to return all valid parent records then do a separate query to find all child of those parents, but combining into 1 LINQ query is where i fail, i was hoping that is possible. In this case it is possible that there are valid child entries of invalid parents, hence need for the question
This should do the trick, (edit: see below for version that doesn’t use Distinct.)
The above code should hopefully generate something quite similar to
what it itself looks like in SQL, maybe with the exception of the
distinct which might cause it to return more data that is actually
needed to be filtered on the client. Something that might become an
issue if there’s a lot data, chiefly if there’s a lot of parents
because it will return duplicates of those)
Here is the query reworked without the distinct call