LINQ:如何将嵌套的层次结构对象转换为扁平化对象 [英] LINQ: How to convert the nested hierarchical object to flatten object

查看:97
本文介绍了LINQ:如何将嵌套的层次结构对象转换为扁平化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用LINQ将嵌套的分层对象转换为扁平对象?我知道我们可以轻松地使用foreach循环来实现这一目标.但是我想知道是否有办法用LINQ编写它.

How to convert the nested hierarchical object to flatten objects by using LINQ? I know that we can easily use foreach loop to achieve that. But I'm wondering if there is a way to write it in LINQ.

class Person{
   public int ID {get;set}
   public string Name {get;set}
   public List<Person> Children {get;}
}

数据:

ID   : 1

Name : Jack

Children

2 | Rose 

3 | Paul

我喜欢将此数据转换为扁平格式,如下所示.

I like to convert this data into flatten format like below.

1 | Jack 

2 | Rose 

3 | Paul

我们如何用Linq做到这一点?

How can we do it with Linq?

推荐答案

如果您希望它压扁任意一棵深厚的人树,我建议采取以下措施:

If you want it to flatten an arbitrarily deep tree of people, I suggest the following:

public IEnumerable<Person> GetFamily(Person parent)
{
    yield return parent;
    foreach (Person child in parent.Children) // check null if you must
        foreach (Person relative in GetFamily(child))
            yield return relative;
}

确实没有什么好方法可以使用LINQ来缩短它,因为匿名lambda不能在不实现Y的情况下递归地调用自己.您可以减少"上述方法来

There isn't really any good way to shorten this with LINQ, because anonymous lambdas can't call themselves recursively without implementing Y. You could "reduce" the above method to

return parent.Children.SelectMany(p => GetFamily(p))
                      .Concat(new Person[] { parent });

或者

yield return parent;
    foreach (Person relative in parent.Children.SelectMany(GetFamily))
        yield return relative;

但这对我来说似乎是不必要的.

but that seems sort of unnecessary to me.

这篇关于LINQ:如何将嵌套的层次结构对象转换为扁平化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆