LINQ To Dictionary

foreach(Dog d in Dogs)
      string name = d.Name;
      int age = a.age;
      foreach(Paw p in d.Paws)
             int pawShape = p.Shape;
             foreach(Toe t in p.Toes)
                  int toeStrength = t.Strength;
                  foreach (ToeNail n in t.ToeNails)
                        int nailRating = n.Rating;
                        string nailContext = n.Context;


I don't wish to use so many foreach loops. How can I extract the required data using LINQ?

I woul like to produce a list like so:
Name PawId PawShape ToeId TwoStrength NailId NailRating NailContext
Fred 123   3          2      3          3        5        solid
Spot 546   8          4      8          4        3        damaged  

It would also be nice if I could put the data in a dictionary using the Name as the Key?
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

Fernando SotoConnect With a Mentor RetiredCommented:

This should give you what you want.

var result = from d in MyDogs
             from p in d.Paws
             from t in p.Toes
             from n in t.ToeNails
             select new { d.Name, d.Age, p.PawID, p.Shape, n.NailID, n.Rating, n.Context };

foreach( var r in result )
    Console.WriteLine(r.Name + " : " + r.Age + " : " + r.PawID + " : " + r.Shape + " : " + r.NailID + " : " + r.Rating + " : " + r.Context);

Open in new window

I am not a LINQ expert, but I use it on a regular basis.
You code look clean and easy to understand the way it is.

I use link for the following situations:
- filtering data
- sorting data
- joining 2 collections together

However, I don't think you can simplify your code by using LINQ for this kind of situations.

Unless every child-object also has a relation to its parent object.
In that case you first need to create a single collection of all the "toenails", and then you can write

from tn in toenails select new with {.name = tn.Toe.Paw.Dog.Name, .PawId = tn.Toe.Paw.ID, ...}
Dennis AriesCEO @ Arkro ITCommented:
On, you will find many examples for Linq.
I think you are looking for something like
in conjuction with to convert it to the dictionary.
Fernando SotoRetiredCommented:
XPUSR, is this issue resolved?
All Courses

From novice to tech pro — start learning today.