C# LInq查询集合内部的集合

C# LInq查询集合内部的集合,c#,linq,linq-to-objects,C#,Linq,Linq To Objects,我的对象包含一个集合集合。我喜欢获取所有子对象ID并将其存储在字符串数组中 main对象包含父对象的列表 父项包含子项的列表 子属性是(Id、名称) 如何使用linq查询MainObject并查找所有子ID并将其存储在字符串数组中?您可以使用SelectMany: var stringArray = MainObject.ListOfParent .SelectMany(p => p.ListOfChildren

我的对象包含一个集合集合。我喜欢获取所有子对象ID并将其存储在字符串数组中

main对象包含父对象的列表

父项包含子项的列表

子属性是(Id、名称)


如何使用linq查询MainObject并查找所有子ID并将其存储在字符串数组中?

您可以使用
SelectMany

var stringArray = MainObject.ListOfParent
                            .SelectMany(p => p.ListOfChildren
                                              .Select(c => c.Id.ToString()))
                            .ToArray()
试试这个

var id =parents.SelectMany(p => p.Children).Select(x => x.Id).ToArray();
var id =parents.SelectMany(p => p.Children).Select(x => x.Id).ToArray();