Reputation: 454
I am trying to select text from a collection that is three of four deep.
RootObject
has a List<ResourceSet>
resourceSets
The resourceSets
has a List<Resources>
resources
The resources
has a List<RouteLeg>
routeLegs
The routLegs
has a List<ItineraryItem>
itineraryItems
The each routeLeg
contains and object called ItineraryItem
and in that object there is a text property.
I am trying to pull out a list of all the text properties on the routeLeg
object. As you can see it is nested pretty deep. I can obviously do this in nested loops..(as shown below) but want something cleaner using Linq to Objects but I am having trouble with the multiple nesting.
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());
}
}
}
}
Upvotes: 6
Views: 4867
Reputation: 564413
You can use SelectMany to fetch the internal items:
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());
Upvotes: 13