How to return ancestors of an object with LINQ?

I have an environment 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 get a list of all the ancestors of the county. Therefore, if the district "1.1.1" is a child of the district "1.1", which is a child of the district "1", receiving ancestors in the district "1.1.1" will return a list containing the objects of the district whose names are "1.1" and "1".

Is this related to the statement of return on profitability (I never understood this completely)? Can this be done on one line?

+3
source share
3 answers

Everything can be done on one line if the line is long enough :)

In this case, it is probably easiest to do this on more than one line:

public IEnumerable<District> Ancestors
{
    get
    {
        District parent = Parent;
        while (parent != null)
        {
            yield return parent;
            parent = parent.Parent;
        }
    }
}

, yield return - 6 # Depth - , # 2. .

+9

, ... "", . ( sql )

SQL

. ""

, , -

oh, linq

ancestors = Districts.Where( d => 
       d.Pedigree.Contains(Id) && 
       d.Pedigree.Length < Pedigree)
       .ToList();

ORM, ,

, , , .....:)

+1

:

static public IEnumerable<T> GetAncestors<T>(this T source, Func<T, T> parentOf)
{
    var Parent = parentOf(source);
    while (Parent != null)
    {
        yield return Parent;
        Parent = parentOf(Parent);
    }
}

Therefore, I can use it for all hierarchies in my application:

public IEnumerable<District> Ancestors
{
    get
    {
        return this.GetAncestors(d => d.Parent);
    }
}

Or expand all the parent nodes of the given TreeView node ...

Node.GetAncestors(node => node.Parent).ToList().ForEach(n => n.Expanded = true);

It is really convenient.

+1
source

Source: https://habr.com/ru/post/1745221/


All Articles