我有一个District类,看起来像这样:
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”的地区对象。
这是否涉及到yield return语句(我从未完全理解过)?它可以一行完成吗?
while (parent != null && !visitedParents.Contains(parent))
- Jon Skeet