本文介绍了如何使用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? */ } }
}

我希望能够获得每个地区的祖先的清单.因此,如果区"1.1.1"是区"1.1"的子级,区"1.1"是区"1"的子级,则在区"1.1.1"上获取祖先将返回一个列表,其中包含名称为"1.1"的区对象"和"1".

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".

这是否涉及yield return语句(我从未完全理解这一点)?可以一行完成吗?

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;
        }
    }
}

如果您想更好地理解yield return,请做一个简短的介绍-Depth中C#第一版的第6章仍然是免费提供的,而这一切都与C#2中的迭代器有关.请从第一版页面.

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.

这篇关于如何使用LINQ返回对象的祖先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 16:16