6

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());
                        }
                    }

                }
            }
1
  • You have a bug... for (int j = 0; j < rs.resources.Count; i++) should be for (int j = 0; j < rs.resources.Count; j++) (you used i instead of j) Commented Sep 11, 2017 at 20:38

1 Answer 1

13

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());
Sign up to request clarification or add additional context in comments.

1 Comment

should the last line be sb.Append(item.instruction.ToString()); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.