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());
}
}
}
}
The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.
LINQ to Objects offers usage of any LINQ query supporting IEnumerable<T>for accessing in-memory data collections without any need of LINQ provider (API) as in case of LINQ to SQL or LINQ to XML.
In a nutshell, LINQ to Objects provides the developer with the means to conduct queries against an in-memory collection of objects. The techniques used to query against such collections of objects are similar to but simpler than the approaches used to conduct queries against a relational database using SQL statements.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With