I work in C# and Entity framework. I have a table in my database named Genre. Here are its attributes: idGenre, name, idParentGenre.
For example. the values would be:
(idGenre = 1, name = "acoustic", idParentGenre=2)
(idGenre = 2, name = "rock", idParentGenre=2)
(idGenre = 3, name = "country", idParentGenre=4)
(idGenre = 4, name = "folk", idParentGenre=5)
(idGenre = 5, name = "someOtherGenre", idParentGenre=5)
As you can see, it's kind of a tree.
Now, I have a method for searching through this table. The input parameter is idGenre and idParentGenre. I should return if the genre (idGenre) is a son/grandchild/grandgrandchild/... of idParentGenre.
For example, I get idGenre=3, idParentGenre=5, I should return true.
However, there isn't recursion in Linq. Is there a way I can do this?
I would make a method to handle this instead of using LINQ:
bool HasParent(int genre, int parent)
{
Genre item = db.Genres.FirstOrDefault(g => g.IdGenre == genre);
if (item == null)
return false;
// If there is no parent, return false,
// this is assuming it's defined as int?
if (!item.idParentGenre.HasValue)
return false;
if (item.idParentGenre.Value == parent)
return true;
return HasParent(item.idParentGenre, parent);
}
This lets you handle this in a single recursive function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With