Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return the ancestors of an object with LINQ?

Tags:

c#

linq

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?

like image 652
Chris Avatar asked May 13 '10 05:05

Chris


1 Answers

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.

like image 80
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet