Reputation: 2048
public class CategoryInModel
{
public int Id { get; set; }
public CategoryInModel Parent { get; set; }
}
I have a class like above. I want to get depth of the Parent object.
Parent object can have various depths. Like:
Parent.Parent.Parent
or
Parent.Parent
How can I find the depth of the parent object?
Upvotes: 0
Views: 253
Reputation: 20373
Based on the logic that a model's depth will be 1 + the parent depth:
public class CategoryInModel
{
public int Id { get; set; }
public CategoryInModel Parent { get; set; }
public int Depth => 1 + ParentDepth;
public int ParentDepth => Parent?.Depth ?? 0;
}
Upvotes: 4
Reputation: 3676
static int GetDepth (CategoryInModel cat, int depth = -1)
{
if (cat == null)
return depth;
else
return GetDepth(cat.Parent, depth + 1);
}
And then to use:
var mod = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel() } } };
Console.WriteLine(GetDepth(mod));
Upvotes: 1