列表

时间:2016-10-18 14:36:37

标签: c# linq

在我的代码中,我有一个ObjectA列表,每个ObjectA都有一个ObjectB列表。我想获得ObjectAs列表中所有ObjectB的一个列表。

如果我有这个对象:

public class ObjectA
{
    public string Name {get; set;}
    public List<ObjectB> Children {get; set;}
}

public class ObjectB
{
    public string ChildName {get; set;}
}

这段代码:

void Main()
{
    var myList = 
        new List<ObjectA>{
            new ObjectA{
                Name = "ItemA 1", 
                Children = new List<ObjectB>{
                        new ObjectB{ChildName = "ItemB 1"},
                        new ObjectB{ChildName = "ItemB 2"}
                    }
            },
            new ObjectA{
                Name = "ItemA 2", 
                Children = new List<ObjectB>{
                        new ObjectB{ChildName = "ItemB 3"},
                        new ObjectB{ChildName = "ItemB 4"}
                    }
            }
        };
    // What code would I put here to concat all the ObjectBs?
}

我希望获得List<ObjectB>ObjectB项:

  

ItemB 1
  ItemB 2
  ItemB 3
  ItemB 4

3 个答案:

答案 0 :(得分:8)

您可以使用SelectMany

var result = mylist.SelectMany(a => a.Children).ToList();

答案 1 :(得分:5)

var allObjectB = myList.SelectMany(x=>x.Children).ToList();

答案 2 :(得分:0)

这是我如何做到的(在我看到SelectMany答案之前......)

http://ideone.com/piypJq

exec sp_updatestats 
相关问题