在集合中查询子集合的Linq方法

7

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

MainObject包含父项列表

父项包含子项列表

子项属性为(Id,Name)

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

3个回答

15

你可以使用SelectMany

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

4

试试这个

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

3
var arrayOfIds = MainObject.ListOfParents
                           .SelectMany(x => x.ListOfChildren)
                           .Select(x => x.Id)
                           .ToArray();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接