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

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-05-13T05:09:07Z Indexed on 2010/05/13 5:14 UTC
Read the original article Hit count: 233

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about c#