我正在尝试从四个深度中的三个集合中选择文本.
RootObject具有List< ResourceSet> resourceSets
resourceSets有一个List< Resources>资源
资源有一个List< RouteLeg> routeLegs
routLegs具有List< ItineraryItem> itineraryItems
每个routeLeg包含名为ItineraryItem的对象,在该对象中有一个text属性.
我试图拉出routeLeg对象上所有文本属性的列表.正如你所看到的,它嵌套得非常深.我显然可以在嵌套循环中执行此操作..(如下所示)但是想要使用Linq to Objects更清洁,但是我遇到了多重嵌套问题.
ResourceSet testst = new ResourceSet(); ResourceSet rs; StringBuilder sb = new StringBuilder(); for (int i = 0; i < _Result.resourceSets.Count; i++) { rs = _Result.resourceSets[i]; for (int j = 0; j < rs.resources.Count; i++) { Resource rec = rs.resources[j]; string test = rec.distanceUnit; for (int k = 0; k < rec.routeLegs.Count; k++) { RouteLeg rl = rec.routeLegs[k]; for (int l = 0; l < rl.itineraryItems.Count; l++) { ItineraryItem ii = rl.itineraryItems[l]; sb.Append(ii.instruction.ToString()); } } } }
解决方法
您可以使用
SelectMany来获取内部项:
var items = result.resourceSets .SelectMany(rs => rs.resources) .SelectMany(res => res.routeLegs) .SelectMany(rl => rl.itineraryItems) foreach(var x in items) sb.Append(x.instruction.ToString());