I have a District class that looks like this:
public class District
{
public int Id { get; set; }
public string Name { get; set; }
public District Parent { get; set; }
public IEnumerable<District> Ancestors { get { /* what goes here? */ } }
}
I would like to be able to get a list of each District's ancestors. So if District "1.1.1" is a child of District "1.1", which is a child of District "1", getting Ancestors on District "1.1.1" would return a list that contains the District objects whose names are "1.1" and "1".
Does this involve the yield return statement (I never totally understood that)? Can it be done in one line?
Everything can be done in one line, if the line is long enough :)
In this case, it's probably simplest done not in one line:
public IEnumerable<District> Ancestors
{
get
{
District parent = Parent;
while (parent != null)
{
yield return parent;
parent = parent.Parent;
}
}
}
Just a brief plug if you want to understand yield return
better - chapter 6 of the first edition of C# in Depth is still available for free, and that's all about iterators in C# 2. Grab it from the first edition page.
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